我有一个由几个带有尾随图标的 sListView组成的。ListTile图标的颜色应根据用户的点击从透明变为绿色。但是,UI 不会根据用户交互进行更新。
是ServiceModel这样的。
class ProviderService extends ChangeNotifier {
final List<String> totalNames = ['Somesh', 'Tarulata', 'Indranil', 'Satyajyoti', 'Biswas', 'Sajal', 'Kumar', 'Slipa', 'Sonam', 'Neelam'];
List<String> _selectedNames = [];
List<String> get selectedNames => _selectedNames;
void updateselectedNames(String name) {
bool isExists = _selectedNames.contains(name);
if (isExists)
_selectedNames.remove(name);
else
_selectedNames.add(name);
notifyListeners();
}
}
Run Code Online (Sandbox Code Playgroud)
事情ListView是这样的。
class Members extends StatelessWidget {
@override
Widget build(BuildContext context) {
ProviderService plService = Provider.of<ProviderService>(context, listen: false);
return Scaffold(
body: SafeArea(
child: Selector<ProviderService, List<String>>( …Run Code Online (Sandbox Code Playgroud) 我正在尝试了解提供程序在颤振中的工作原理,但我仍然没有弄清楚如何使用状态的构造函数来初始化状态。有什么建议吗?
这是构造函数正在监视的类
class Counter extends ChangeNotifier{
int _count;
Counter(int initValue){
_count=initValue;
}
void increment() {
++_count;
notifyListeners();
}
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试制作 MultiProvider。我不知道错误在哪里。我是 Dart 和 Flutter 新手。尝试自己修复它,但无法修复它。当我运行该项目时,它卡在错误屏幕上。我附上带有问题的图片。
\n\n这是我的代码 main.dart 文件
\nimport \'package:firebase_core/firebase_core.dart\';\nimport \'package:flutter/material.dart\';\nimport \'package:provider/provider.dart\';\nimport \'package:vendorapp/providers/auth_providers.dart\';\nimport \'package:vendorapp/screens/homescreen.dart\';\nimport \'package:vendorapp/screens/registerscreen.dart\';\nimport \'package:vendorapp/screens/splashscreen.dart\';\n\nvoid main() async {\n //Provider.debugCheckInvalidValueType = null;\n WidgetsFlutterBinding.ensureInitialized();\n await Firebase.initializeApp();\n\n runApp( MultiProvider(\n providers:[\n Provider (create: (_) => AuthProvider()),\n ],\n child: MyApp(),\n )\n );\n}\n\nclass MyApp extends StatelessWidget {\n const MyApp({key}) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n debugShowCheckedModeBanner: false,\n theme: ThemeData(\n primaryColor: Colors.greenAccent,\n fontFamily: \'Poppins\',\n ),\n initialRoute: SplashScreen.id,\n routes: {\n SplashScreen.id: (context) => SplashScreen(),\n RegisterScreen.id: (context) => RegisterScreen(),\n …Run Code Online (Sandbox Code Playgroud) 我正在构建一个 Flutter 应用程序,它有一个主要提供程序,其中包含会话 id 和许多其他“全局”属性。
class AppService with ChangeNotifier {
String _sessionId;
String _name;
...
}
Run Code Online (Sandbox Code Playgroud)
我还有其他几个处理非常具体的事情的提供程序(AppService 也开始变得很大,所以必须将其拆分出来)。
我的问题是如何从其他服务(例如将它们命名为 ServiceB、ServiceC 和 ServiceD)访问 AppService 中的 _sessionId、名称和其他属性?是否可以从另一个(例如 ServiceB)调用 AppService 中的函数?
class ServiceB with ChangeNotifier {
...
}
class ServiceC with ChangeNotifier {
...
}
class ServiceD with ChangeNotifier {
...
}
Run Code Online (Sandbox Code Playgroud)
我看到有人提到ChangeNotifierProxyProvider,但不确定这是否会给我带来我需要的东西,因为我需要访问多个其他类中的 AppService 。
这是我的提供商当前的设置方式。
MultiProvider(
providers: [
ChangeNotifierProvider<AppService>(
create: (_) => AppService(),
),
ChangeNotifierProvider<ServiceB>(
create: (_) => ServiceB(),
),
ChangeNotifierProvider<ServiceC>(
create: (_) => ServiceC(),
),
ChangeNotifierProvider<ServiceD>(
create: (_) => …Run Code Online (Sandbox Code Playgroud) 我/正面临这个问题。有人可以帮忙吗?谢谢 第一页
将提供者作为参数传递给小部件是最佳实践吗?
我知道我们可以从小部件内直接访问提供程序。但看到几个代码片段将提供程序作为参数传递给子小部件。它优化了代码吗?或者有什么可能的泄漏?
我用来Provider向屏幕和警报对话框提供一些数据。知道它AlertDialog是在小部件树之外的,我添加了一个ChangeNotifierProvider作为该对话框的包装小部件。但即使我确保值在提供者状态下更新,UI 仍然没有改变。
代码片段:
showTextDialog(BuildContext context) {
final myModel = Provider.of<ServicesProvider>(context, listen: false);
return showDialog(
context: context,
builder: (_) => ChangeNotifierProvider.value(
value: myModel,
child: AlertDialog(
content: IntrinsicHeight(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
children: [
Radio(
value: '0',
groupValue: myModel.paymentMethod,
onChanged: (value) => myModel.setPaymentMethod('0'),
activeColor: ColorResources.PRIMARY_COLOR,
toggleable: true,
),
SizedBox(width: responsiveWidth(5)),
Text("Radio Button 1"),
],
),
SizedBox(height: responsiveHeight(10)),
Row(
children: [
Radio(
value: '1',
groupValue: myModel.paymentMethod,
onChanged: (value) => myModel.setPaymentMethod('1'),
activeColor: ColorResources.PRIMARY_COLOR,
toggleable: true, …Run Code Online (Sandbox Code Playgroud) 我正在尝试实现一个注销页面。因此,当用户单击导航中的注销按钮时,将调用以下代码:
Class Logout extends StatelessWidget {
@override
Widget build(BuildContext context) {
final provider = Provider.of<SignInProvider>(context, listen: true);
Future.delayed(Duration(seconds: 5), () async {
provider.isLoggedIn = false;
provider.notifyListeners();
Navigator.pushReplacement(
context, new MaterialPageRoute(builder: (context) => LoginGate()));
});
return Center(child: CircularProgressIndicator());
}
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
The following assertion was thrown building MainScreen(dirty, dependencies: [_InheritedProviderScope<SelectedIndex?>, _InheritedProviderScope<SignInProvider?>], state: _MainScreenState#6a8ce):
setState() or markNeedsBuild() called during build.
Run Code Online (Sandbox Code Playgroud)
我尝试添加延迟,希望能解决问题,但没有帮助。希望获得有关如何处理此问题的帮助。
使用 NavigationRail 显示注销按钮
const NavigationRailDestination(
icon: Icon(Icons.logout),
label: Text('Logout'),
),
Run Code Online (Sandbox Code Playgroud)
使用以下方式调用注销小部件:
child: Row(
children: [
NavigationRailExample(),
const VerticalDivider(thickness: 1, width: 1), …Run Code Online (Sandbox Code Playgroud) 我收到此错误消息:
Unhandled Exception: A ModeManager was used after being disposed.
Run Code Online (Sandbox Code Playgroud)
我将ChangeNotifier(类ModeManager)与ChangeNotifierProvider一起使用。我在其中创建 Provider 的 Build 方法如下所示:
@override
Widget build(BuildContext context) {
return !_isLoaded ? Center(child: CircularProgressIndicator()) : ChangeNotifierProvider(
create: (_) => ModeManager(_appUser),
child: Scaffold(
appBar: AppBar(
title: Text('Connect Spotify'),
),
body: AddSpotifyScreenBody(),
),
);
}
Run Code Online (Sandbox Code Playgroud)
我使用 provider 的小部件看起来像这样:
class _AddSpotifyScreenBodyState extends State<AddSpotifyScreenBody> {
@override
Widget build(BuildContext context) {
var provider = Provider.of<ModeManager>(context);
return Center(
child: Padding(
padding: EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Text(provider.isCollecting ? 'COLLECTING …Run Code Online (Sandbox Code Playgroud) 我想要一个“设置”屏幕,我可以在其中选择要返回到第一个屏幕的颜色。
当“设置”屏幕关闭时,我无法更新第一个屏幕。
我使用提供程序作为更改通知程序。但我看不到如何触发第一个屏幕的更新。第三个按钮创建一个更新屏幕的事件,但这可以自动完成吗?
我错过了什么...?
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyApp());
Color bgColor = Colors.yellow[100];
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: MyHomeScreen());
}
}
class MyHomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => ColorModel()),
],
child: Consumer<ColorModel>(builder: (context, colorModel, child) {
return Scaffold(
appBar: AppBar(title: Text('Thanks for your help :)')),
body: Container(
constraints: BoxConstraints.expand(),
color: bgColor,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('Change background color …Run Code Online (Sandbox Code Playgroud) 我试图在一个类中使用periodic该类的方法Timer,该类扩展了该类ChangeNotifier(包Provider),使我的变量time每秒都在减少。
如果我不添加NotifyListeners重绘占用该time属性的所有小部件的方法,则此方法可以正常工作,例如:
class PriceProvider extends ChangeNotifier{
int _time = 60;
int get time{
return _time;
}
void chronometer(){//method which activate the timer
Timer _timer = Timer.periodic(const Duration(seconds: 1), (Timer timer){
print(DateTime.now());//I print the date so you can see how often the code is executed
_time += -1;//decrease time
if(_time == 0){
_time = 60;
}
// notifyListeners();
});
}
}
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我取消对该NotifyListeners方法的注释,代码开始以指数方式每秒执行越来越多的次数(例如,首先执行一次,然后两次,然后 5 次,然后 …
在 Flutter 中使用 Provider 时出现以下错误:
The following assertion was thrown while dispatching notifications for CampaignProvider: setState() or markNeedsBuild() called during build. This _InheritedProviderScope<CampaignProvider?> widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a …