АР
PageB
, тот же самый инстанс
Size: a a a
АР
PageB
, тот же самый инстансАР
MU
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyService {
final int importantValue;
MyService(this.importantValue);
String getFoo() {
return 'foo $importantValue';
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: PageA(),
);
}
}
class PageA extends StatelessWidget {
final int importantValue = 42;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Provider(
create: (context) => MyService(importantValue),
child: Builder(
build: (context) => RaisedButton(
child: Text('To PageB'),
onPressed: () {
// Беру сервис с текущей страницы
final myService = context.read<MyService>();
Navigator.push(context, MaterialPageRoute(builder: (context) =>
// Пихаю его в новую страницу
Provider.value(
value: myService,
child: PageB(),
)
));
},
),
),
),
);
}
}
class PageA extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Text(context.read<MyService>().getFoo()),
);
}
}
АР
PD
context.read<MyService>().getFoo()
. Это сработало бы, если бы на PageB был бы тот же контекст, что и в месте вызова Navigator.push
, но очевидно, что это не такАР
АР
PD
VV
child: PageA()
на child: Page
B() заменить?АР
PD
child: PageA()
на child: Page
B() заменить?PD
АР
PD
PD
VV
PD
context.read<MyService>()
АР
PD
АР