Created
February 27, 2024 18:50
-
-
Save brasizza/c7b0c351c6fb6de0f8732415fdfb547f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:provider/provider.dart'; | |
void main() { | |
const isCat = true; | |
runApp( | |
Provider<Animal>( | |
create: (context) { | |
debugPrint('create'); | |
return isCat ? Cat(name: 'Whiskers', meows: 'meow') : Dog(name: 'Fido', barks: 'woof'); | |
}, | |
builder: (context, _) => MaterialApp( | |
home: Scaffold( | |
appBar: AppBar( | |
title: const Text('Hello World'), | |
), | |
body: Column( | |
children: [ | |
Visibility( | |
visible: (context.read<Animal>() is Dog), | |
replacement: const CatWidget(), | |
child: const DogWidget(), | |
), | |
const CommonWidget(), | |
], | |
), | |
), | |
), | |
), | |
); | |
} | |
class CommonWidget extends StatelessWidget { | |
const CommonWidget({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return Text( | |
context.read<Animal>().name, | |
); | |
} | |
} | |
class DogWidget extends StatelessWidget { | |
const DogWidget({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return Text( | |
(context.read<Animal>() as Dog).barks, | |
); | |
} | |
} | |
class CatWidget extends StatelessWidget { | |
const CatWidget({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return Text( | |
(context.read<Animal>() as Cat).meows, | |
); | |
} | |
} | |
abstract class Animal { | |
Animal({required this.name}); | |
String name; | |
} | |
class Dog extends Animal { | |
Dog({ | |
required super.name, | |
required this.barks, | |
}); | |
String barks; | |
} | |
class Cat extends Animal { | |
Cat({ | |
required super.name, | |
required this.meows, | |
}); | |
String meows; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment