我使用 flutter Provider 包为扩展 ChangeNotifier 的类创建可观察的状态行为..
我有一个扩展 StatelessWidget 的 Person 类,因此我可以创建一个 Person 小部件。
我第一次在 builder 方法中创建了一个 Person 类的实例
ChangeNotifierProvider<Person>(
builder: (context) => Person(name: 'Jim', age: 1),
),
又一次,作为孩子的小部件树更深,但另一个人自然没有听众......
所以我试图将我的第二个 Person 包装在树中的另一个 ChangeNotifierProvider 中,但是我收到了这个错误:
======== Exception caught by widgets library =======================================================
The following assertion was thrown building InheritedProvider<Person>(dirty):
A build function returned null.
The offending widget is: InheritedProvider<Person>
Build functions must never return null.
也许问题是,我有 2 个相同类型的 ChangeNotifierProviders(一个在顶部名为“Jim”,一个在名为“Bob”的 Level 2 类中),它不知道哪个是哪个以及如何更新它们状态? 是否可以创建 2 个相同的 ChangeNotifierProviders 类型的类,只是名称不同?完整代码如下:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<Data>(
builder: (context) => Data(),
),
ChangeNotifierProvider<Person>(
builder: (context) => Person(name: 'Jim', age: 1),
),
],
child: MaterialApp(
home: Scaffold(
appBar: AppBar(
title: MyText(),
),
body: Level1(),
),
),
);
}
}
class Person extends StatelessWidget with ChangeNotifier {
String name;
int age;
Person({this.name, this.age});
void increaseAge() {
print(age);
this.age++;
notifyListeners();
}
@override
Widget build(BuildContext context) {
return Container(
child: Text(
'My name is $name and my age is: ${age.toString()}',
),
);
}
}
class Level1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: [
Level2(),
FlatButton(
onPressed: () {
print(Provider.of<Person>(context).age);
Provider.of<Person>(context).increaseAge();
},
child: Text('Increase person age!'),
),
Text(
'My name is ${Provider.of<Person>(context).name} and my age is ${Provider.of<Person>(context).age}'),
],
);
}
}
class Level2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: [
MyTextField(),
Level3(),
ChangeNotifierProvider<Person>(
builder: (context) => Person(
name: 'Bob',
age: 33,
),
),
],
);
}
}
class Level3 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text(Provider.of<Data>(context).data);
}
}
class MyText extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text(Provider.of<Data>(context, listen: false).data);
}
}
class MyTextField extends StatelessWidget {
@override
Widget build(BuildContext context) {
return TextField(
onChanged: (newText) {
Provider.of<Data>(context).changeString(newText);
},
);
}
}
class Data extends ChangeNotifier {
String data = 'Some data';
void changeString(String newString) {
data = newString;
notifyListeners();
}
}