在textField小部件中输入一些文本后,我在更新Level3类中的文本小部件时遇到问题。 感谢您的帮助
在以下代码中公开数据:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
// home: TasksScreen(),
home: ChangeNotifierProvider<Data>(
create: (context) => Data(),
child: Scaffold(
appBar: AppBar(
title: Container(
child: MyText(),
),
),
body: Level1(),
),
),
);
}
}
在下面的类中为模型数据创建数据类
class Data extends ChangeNotifier {
String data = 'this data';
void changeString(String newString) {
data = newString;
print(newString);//don't print anything after typing in textFild
print(data);//don't print either
notifyListeners();
}
}
我想在下面的代码中在MyTextField中使用Data对象属性
但似乎不会触发Provider.of<Data>(context).changeString(newValue)
class MyTextField extends StatelessWidget {
@override
Widget build(BuildContext context) {
return TextField(
onChanged: (newValue) {
print(newValue);//print newValue correctly
Provider.of<Data>(context).changeString(newValue);
},
);
}
}
class Level3 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: Text(
//this part don't update as typing in textField
Provider.of<Data>(context).data,
//will return an instance of Provider
//type found in the context that is sent as a parameter
),
),
);
}
}
答案 0 :(得分:0)
您可以尝试
(context.watch<Data>().data).toString();
答案 1 :(得分:0)
您可以在下面复制粘贴运行完整代码
在onChanged
中,您可以使用listen: false
代码段
return TextField(
onChanged: (newValue) {
print(newValue); //print newValue correctly
Provider.of<Data>(context, listen: false).changeString(newValue);
},
);
工作演示
完整代码
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Data extends ChangeNotifier {
String data = 'this data';
void changeString(String newString) {
data = newString;
print(newString); //don't print anything after typing in textFild
print(data); //don't print either
notifyListeners();
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
// home: TasksScreen(),
home: ChangeNotifierProvider<Data>(
create: (context) => Data(),
child: Scaffold(
appBar: AppBar(
title: Container(
child: MyTextField(),
),
),
body: Level3(),
),
),
);
}
}
class MyTextField extends StatelessWidget {
@override
Widget build(BuildContext context) {
return TextField(
onChanged: (newValue) {
print(newValue); //print newValue correctly
Provider.of<Data>(context, listen: false).changeString(newValue);
},
);
}
}
class Level3 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: Text(
//this part don't update as typing in textField
Provider.of<Data>(context).data,
//will return an instance of Provider
//type found in the context that is sent as a parameter
),
),
);
}
}
void main() {
runApp(MyApp());
}