【问题标题】:Could not find the correct Provider<List<UserData>> above this myorder Widget在这个 myorder 小部件上方找不到正确的 Provider<List<UserData>>
【发布时间】:2021-12-24 17:34:16
【问题描述】:

我正在尝试使用流提供程序读取数据,但出现错误:

错误:在这个 myorder Widget 上方找不到正确的 Provider

发生这种情况是因为您使用了不包含提供程序的 BuildContext 你的选择。有几种常见的情况:

  • 您在main.dart 中添加了一个新提供程序并执行了热重载。 要解决此问题,请执行热重启。
  • 您尝试读取的提供程序位于不同的路径中。

提供者是“范围的”。因此,如果您在路线内插入提供者,那么 其他路由将无法访问该提供程序。

  • 您使用了 BuildContext,它是您尝试读取的提供程序的祖先。

确保 myorder 在您的 MultiProvider/Provider 下。 这通常发生在您创建提供程序并尝试立即读取它时。

例如,而不是:

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
final firestoreservice _db= firestoreservice();
runApp(
  MultiProvider (
  providers:[
ChangeNotifierProvider(
create:(context)=>productstore(),),
    ChangeNotifierProvider(
      create:(context)=>selectedDropdownItems(),),
    ChangeNotifierProvider(
      create:(context)=>userprovider(),),
    ChangeNotifierProvider(
      create:(context)=>uploadProd()),
     StreamProvider(create: (BuildContext context)=>_db.getUserList(), initialData: null,)
],
  //ChangeNotifierProvider(
  //create:(context)=>productstore(),
  child: MaterialApp(
    debugShowCheckedModeBanner: false,
    title: 'ROW',
    theme: ThemeData(

      primarySwatch: Colors.red,
    ),
    home:users(),
  ),

),
);
}

class UserData {
UserData ({ this.email,this.id,this.password,this.name});
String? email;
String? id;
String? password;
String? name;


UserData.fromJson(Map<String, dynamic> parsedJSON)
        :name = parsedJSON['name'],
         email = parsedJSON['email'];
}

class firestoreservice {
FirebaseFirestore _db = FirebaseFirestore.instance;
Stream<List<UserData>> getUserList() {
 return _db.collection('users')
     .snapshots()
     .map((snapshot) =>
     snapshot.docs
         .map((document) => UserData.fromJson(document.data())).toList()
 );
}


}

class users extends StatelessWidget{
@override
Widget build(BuildContext context) {
  var store = Provider.of<List<UserData>>(context,listen:false);
 

  return  Container(
    width: MediaQuery.of(context).size.width,
    height: MediaQuery.of(context).size.height,
    decoration: BoxDecoration( color: Colors.white,
      // border: Border.all(color: Colors.red)
    ),
    child:
    ListView(
      children: [
        Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 4.0,bottom: 4.0),
            ),
            ListView.builder(
                shrinkWrap: true,
                physics: ScrollPhysics(),
                
                itemCount:store.length,
                itemBuilder:(context, index)
                {UserData userdata= store[index];

                  return Padding(
                    padding: const EdgeInsets.only(top: 4.0,bottom: 4.0),
                    child: Container(
                      height: 220,
                      width: MediaQuery.of(context).size.width,
                      decoration: BoxDecoration(
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black,
                            blurRadius: 2.0,
                            spreadRadius: 0.0,
                            offset: Offset(2.0, 2.0),
                          )
                        ],
                        color: Colors.white,
                        //border: Border.all(color: Colors.red)
                      ),
                      child: Column(
                        children: [
                          Row(
                            //mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Padding(
                                padding: const EdgeInsets.only(top: 4.0,bottom: 4.0,left: 10.0),
                               
                                child: Text(userdata.name.toString(),style: TextStyle(color: Colors.red,fontSize: 10, fontWeight: FontWeight.bold),),
                              ),
                              Padding(
                                padding: const EdgeInsets.only(top: 4.0,bottom: 4.0,left: 10.0),
                                
                                child: Text(userdata.email.toString(),style: TextStyle(color: Colors.red,fontSize: 10, fontWeight: FontWeight.bold),),
                              ),


                            ],
                          ),


                        ],
                      ),

                    ),
                  );
                }
            ),
          ],
        ),
      ],
    )
    ,
  );


}
}

【问题讨论】:

标签: flutter dart google-cloud-firestore provider


【解决方案1】:

查看此示例,这是UI 文件:

import 'package:custom/second.dart';
import 'package:custom/second.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [ChangeNotifierProvider(create: (context) => UserProvider())],
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView.builder(
          itemCount: context.watch<UserProvider>().list.length,
          itemBuilder: (context, index) => ListTile(
                title:
                    Text("${context.watch<UserProvider>().list[index].name}"),
                subtitle:
                    Text("${context.watch<UserProvider>().list[index].email}"),
              )),
      floatingActionButton: FloatingActionButton(
        onPressed: () => context
            .read<UserProvider>()
            .setUser(User("demo2", "Demo@demo.com")),
        child: Icon(Icons.add),
      ),
    );
  }
}

这是此列表的Provider 文件

import 'package:flutter/cupertino.dart';

class UserProvider extends ChangeNotifier {
  List<User> _list = [User("User", "user@demo.com")];

  List<User> get list => _list;

  setUser(User value) {
    _list.add(value);
    notifyListeners();
  }
}

class User {
  String name;
  String email;

  User(this.name, this.email);
}

【讨论】:

  • 我将 Multiprovider 包装在 Builder 中,但仍然出现相同的错误。请提供更多帮助
  • 在这行 Provider.of> 你必须传递类,它扩展像 Provider.of 这样的 ChangeNotifier 并且在那个类中你可以为 List 创建 Getter 和 Setter跨度>
  • 请你重写一个简单的例子。那会更有帮助
  • 好的,我将发布一个示例代码,我将在其中获取某些内容并将其传递给 UI
  • 仍在等待帖子。希望它会很快
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 2021-08-24
  • 2021-10-27
  • 2021-02-26
  • 2021-01-27
  • 1970-01-01
相关资源
最近更新 更多