我正在尝试实现一些谷歌广告,感谢AdMob,我正在使用Provider插件。当我使用provider.value时,我的代码不起作用。我真的不明白为什么。请帮忙。
这是我的代码:
import 'package:distance_meter/ad_state.dart';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:provider/provider.dart';
import 'pages/loading_screen.dart';
import 'package:flutter/services.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final initFuture = MobileAds.instance.initialize();
final adState = AdState(initFuture);
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
runApp(
Provider.value(
value: (context, child) => MaterialApp(home: Loading())
)
);
}
这就是错误:
======== Exception caught by widgets library =======================================================
The following assertion was thrown building Provider<(dynamic, dynamic) => MaterialApp>(value: Closure: (dynamic, dynamic) => MaterialApp, dirty):
Provider<(dynamic, dynamic) => MaterialApp> used outside of MultiProvider must specify a child
'package:provider/src/inherited_provider.dart':
Failed assertion: line 156 pos 7: 'builder != null || child != null'
The relevant error-causing widget was:
Provider<(dynamic, dynamic) => MaterialApp> file:///D:/MyProjects-active/distance-meter/lib/main.dart:18:14
When the exception was thrown, this was the stack:
#2 InheritedProvider.buildWithChild (package:provider/src/inherited_provider.dart:156:7)
#3 SingleChildStatelessWidget.build (package:nested/nested.dart:259:41)
#4 StatelessElement.build (package:flutter/src/widgets/framework.dart:4569:28)
#5 SingleChildStatelessElement.build (package:nested/nested.dart:279:18)
#6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)
...
====================================================================================================
确保检查出使用Provider.value((的正确方法
该构造函数需要一个值(您希望使其小部件子树可用的Provider实例,之前已实例化(和一个构造器函数(您在提供程序下实际构建的内容(
您的语法应该是
final _instanceOfYourProvider = YourProvider();
Provider<YourProvider>.value(
value: _instanceOfYourProvider,
builder: (context, child) => MaterialApp(home: Loading()),
);
在任何情况下,在实例化小部件树上的提供者时都要小心。最好将它实例化在适用于您的用例的最低级别之上。(例如,如果你只需要一个屏幕,就在屏幕上方实例化它(