我正在使用Provider,并且试图在ChangeNotifierProvider的嵌套对象下调用方法(在嵌套在Aircraft中的Seat中调用updateColor())下更新我的小部件。
如Flutter Provider Nested Objects question中所述,我尝试使用ChangeNotifierProxyProvider,但没有成功。
当我调用updateColor()时,如何确保小部件已更新?
代码示例:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
main() {
runApp(MultiProvider(providers: [
ChangeNotifierProvider<Aircraft>(create: (_) => Aircraft()),
], child: MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Consumer<Aircraft>(builder: (context, aircraft, _) {
return Column(
children: <Widget>[
Text('${aircraft.aircraftManufacturer.toString()}'),
Text('${aircraft.emptyWeight}'),
Text('${aircraft.length}'),
Column(
children: aircraft.seats.entries.map((seat) {
return Text(
'Row ${seat.key} is Class: ${seat.value.seatClass.toString()}, '
+ 'emergencyExitSeat: ${seat.value.emergencyExitSeat.toString()}, '
+ ' emergencyExitSeat: ${seat.value.seatColor.toString()},');
}).toList()),
Column(
children: aircraft.seats.entries.map((seat) {
return RaisedButton(
onPressed: () => seat.value.updateColor(),
child: Text('Change color for ${seat.key}'),
);
}).toList())
],
);
}),
),
),
);
}
}
enum Manufacturer { Airbus, Boeing, Embraer }
enum SeatClass { First, Business, Economy }
class Aircraft extends ChangeNotifier {
Manufacturer _aircraftManufacturer;
double _emptyWeight;
double _length;
Map<int, Seat> _seats;
Manufacturer get aircraftManufacturer => _aircraftManufacturer;
double get emptyWeight => _emptyWeight;
double get length => _length;
Map<int, Seat> get seats => _seats;
Aircraft() {
_aircraftManufacturer = Manufacturer.Airbus;
_emptyWeight = 190.0;
_length = 66.80;
_seats = new Map<int, Seat>();
_seats.putIfAbsent(
1, () => new Seat(SeatClass.First, false, Color(0xFF42A5F5)));
_seats.putIfAbsent(
2, () => new Seat(SeatClass.Business, false, Color(0xFF42A4F5)));
_seats.putIfAbsent(
3, () => new Seat(SeatClass.Economy, false, Color(0xFF42A3F5)));
_seats.putIfAbsent(
4, () => new Seat(SeatClass.Economy, true, Color(0xFF42A2F5)));
}
}
class Seat extends ChangeNotifier {
SeatClass _seatClass;
bool _emergencyExitSeat;
Color _seatColor;
Seat(SeatClass seatClass, bool emergencyExitSeat, Color seatColor) {
_seatClass = seatClass;
_emergencyExitSeat = emergencyExitSeat;
_seatColor = seatColor;
}
SeatClass get seatClass => _seatClass;
bool get emergencyExitSeat => _emergencyExitSeat;
Color get seatColor => _seatColor;
void updateColor() {
_seatColor = Color(0xFF9EB26E);
print('Color updated');
notifyListeners();
}
}
答案 0 :(得分:1)
为什么还要将ChangeNotifier
设置为座席,它不需要直接notifyListeners
,因为它是嵌套和创建 { {1}},因此您只需将Aircraft
设为Aircraft
,并在ChangeNotifier
中提供一种更改颜色的方法(Seat
就足够了):
setter