我正在重构应用以使用堆叠式应用,但有问题。状态似乎在小部件之间传递不正确。
我在要影响的小部件树顶部添加了ViewModelBuilder。
return ViewModelBuilder<vehicleData>.reactive(
builder: (context, model, child){
return Container(
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: InkWell(
splashColor: Colors.blueGrey,
child: Card(
//color: Colors.blueGrey,
child: ListTile(
leading: AspectRatio(
aspectRatio: 0.8,
child: Image.network(
//data.images,
snapshot.data.documents[index]['icon'],
height: 500,
//width: 300,
fit: BoxFit.contain,
)
),
title: Text(
//data.make,
snapshot.data.documents[index]['make'],
textAlign: TextAlign.start,
style: TextStyle(fontSize: 18.0,
fontWeight: FontWeight.bold,),
),
onTap: (){
Navigator.push(context, MaterialPageRoute(builder: (context) =>
//ProformaScreen(data.make),
ProformaScreen(snapshot.data.documents[index]['make']),
),
);
model.setModel(snapshot.data.documents[index]['model']);
} ,
),
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.blueGrey),
borderRadius: BorderRadius.circular(10),
),
),
),
);
},
viewModelBuilder: ()=> vehicleData(),
);
这将调用model.setModel并根据所选汽车分配模型。
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:core';
import 'package:stacked/stacked.dart';
class vehicleData extends BaseViewModel{
String _make;
String _images;
var _model;
setModel(var model){
_model = model;
print ('This is the Model of the Car \n');
print (_model);
notifyListeners();
}
setMake(String make){
_make = make;
notifyListeners();
}
setImages(String images){
_images = images;
notifyListeners();
}
get getModel => print('This is within the Get ' + _model);
get getMake => _make;
get getImage => _images;
}
两个print语句都返回正确的模型,我仍然可以看到它们。 但是当我尝试在另一个页面模型中使用ViewModelBuilder调用时,返回null:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:gerente_loja/core/services/vehicle_data.dart';
import 'package:stacked/stacked.dart';
class menuModel extends StatefulWidget {
@override
_menuModelState createState() => _menuModelState();
}
class _menuModelState extends State<menuModel> {
var carModel;
@override
Widget build(BuildContext context) {
String selectModel;
return ViewModelBuilder<vehicleData>.reactive(
builder: (context, modelView, child){
return Padding(
padding: const EdgeInsets.only(left: 16.0, right: 16.0),
child: Container(
decoration: BoxDecoration(border: Border.all(color: Colors.black),
borderRadius: BorderRadius.circular(25.0)
),
padding: EdgeInsets.only(left: 50.0, right: 16.0),
child: DropdownButton(
hint: Text('Ano'),
dropdownColor: Colors.transparent,
elevation: 5,
icon: Icon(Icons.arrow_drop_down),
isExpanded: true,
iconSize: 36.0,
value: selectModel,
onChanged: (value){
setState(() {
print (modelView.getModel);
selectModel = value;
});
},
items: carModel.map((value) {
return DropdownMenuItem (
value: value,
child: Text(value));
}).toList(),
),
),
);
},
viewModelBuilder: ()=> vehicleData(),
);
}
}
打印(modelView.getModel);一片空白。 有人知道为什么模型返回null吗?我看起来很难解决,但不知道为什么。