Flutter Merging List of Images - list

I was working on merging few images and display it as one.
I have two dart files one is for adding images and other is for displaying the merged result.
first file code is,
class SingleImageUpload extends StatefulWidget {
#override
_SingleImageUploadState createState() {
return _SingleImageUploadState();
}
}
class _SingleImageUploadState extends State<SingleImageUpload> {
List<Object> images = List<Object>();
File _selectedFile;
bool _inProcess = false;
Map data = {};
Readerservice _readerservice;
#override
void initState() {
// TODO: implement initState
super.initState();
setState(() {
images.add("Add Image");
images.add("Add Image");
images.add("Add Image");
images.add("Add Image");
});
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
debugShowCheckedModeBanner: false,
home: new Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
leading: Padding(
padding: EdgeInsets.only(left: 12),
child: IconButton(
icon: Icon(Icons.arrow_back_ios,
color: Colors.black,
size: 30,),
onPressed: () {
Navigator.pushNamed(context, '/');
},
),
),
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children:<Widget>[
Text('Basic AppBar'),
]
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.more_vert,
color: Colors.black,
size: 30,),
onPressed: () {
print('Click start');
},
),
],
),
body:
Column(
children: <Widget>[
SizedBox(height: 10),
Row(children: <Widget>[
Text('Image',
style: TextStyle(
color: Colors.black,
fontSize: 33,
fontWeight: FontWeight.bold,
)),
Text('Merger',
style: TextStyle(
color: Colors.orange,
fontSize: 33,
fontWeight: FontWeight.bold,
)),
]),
SizedBox(height: 40),
Text(' merge it here'),
SizedBox(height: 10),
Expanded(
child: buildGridView(),
),
RaisedButton(
textColor: Colors.white,
color: Colors.orange,
child: Text("Finish",
style: TextStyle(fontSize: 15),),
onPressed: () {
pasimage();
},
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(8.0),
),
),
],
),
),
);
}
Widget buildGridView() {
return GridView.count(
shrinkWrap: true,
crossAxisCount: 3,
childAspectRatio: 1,
children: List.generate(images.length, (index) {
if (images[index] is ImageUploadModel) {
ImageUploadModel uploadModel = images[index];
return Card(
clipBehavior: Clip.antiAlias,
child: Stack(
children: <Widget>[
Image.file(
uploadModel.imageFile,
width: 300,
height: 300,
),
Positioned(
right: 5,
top: 5,
child: InkWell(
child: Icon(
Icons.remove_circle,
size: 20,
color: Colors.red,
),
onTap: () {
setState(() {
images.replaceRange(index, index + 1, ['Add Image']);
});
},
),
),
],
),
);
} else {
return Card(
child: IconButton(
icon: Icon(Icons.add),
onPressed: () {
//popup
showDialog(
context: context,
builder: (context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
elevation: 16,
child: Container(
height: 180.0,
width: 330.0,
child: ListView(
children: <Widget>[
SizedBox(height: 20),
//Center(
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Text(
"Add a Receipt",
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 24,
color: Colors.black,
fontWeight: FontWeight.bold),
),
),
// ),
SizedBox(height: 20),
FlatButton(
child: Text(
'Take a photo..',
textAlign: TextAlign.left,
style: TextStyle(fontSize: 20),
),
onPressed: () {
_onAddImageClick(index,ImageSource.camera);
Navigator.of(context).pop();
// picker.getImage(ImageSource.camera);
},
textColor: Colors.black,
),
FlatButton(
child: Text(
'Choose from Library..',
style: TextStyle(fontSize: 20),
textAlign: TextAlign.left,
),
onPressed: () {
_onAddImageClick(index,ImageSource.gallery);
Navigator.of(context).pop();
},
textColor: Colors.black,
),
],
),
),
);
},
);
//pop ends
},
),
);
}
}),
);
}
Future _onAddImageClick(int index, ImageSource source ) async {
setState(() {
_inProcess = true;
});
File image = await ImagePicker.pickImage(source: source);
if(image != null){
File cropped = await ImageCropper.cropImage(
sourcePath: image.path,
maxWidth: 1080,
maxHeight: 1080,
compressFormat: ImageCompressFormat.jpg,
androidUiSettings: AndroidUiSettings(
toolbarColor: Colors.black,
toolbarWidgetColor: Colors.white,
//toolbarTitle: "RPS Cropper",
statusBarColor: Colors.deepOrange.shade900,
backgroundColor: Colors.black,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false
),
iosUiSettings: IOSUiSettings(
minimumAspectRatio: 1.0,
)
);
this.setState((){
_selectedFile = cropped ;
_inProcess = false;
});
} else {
this.setState((){
_inProcess = false;
});
}
getFileImage(index);
}
void getFileImage(int index) async {
// var dir = await path_provider.getTemporaryDirectory();
setState(() {
ImageUploadModel imageUpload = new ImageUploadModel();
imageUpload.isUploaded = false;
imageUpload.uploading = false;
imageUpload.imageFile = _selectedFile;
imageUpload.imageUrl = '';
images.replaceRange(index, index + 1, [imageUpload]);
});
}
void pasimage(){
Navigator.pushReplacementNamed(context, '/crop',arguments: {
'imageList':ImagesMerge(
images,///required,images list
direction: Axis.vertical,///direction
backgroundColor: Colors.black26,///background color
fit: false,///scale image to fit others
),
});
}
}
class ImageUploadModel {
bool isUploaded;
bool uploading;
File imageFile;
String imageUrl;
ImageUploadModel({
this.isUploaded,
this.uploading,
this.imageFile,
this.imageUrl,
});
}
when I tap the finish button after adding the images it shows an error
The following _TypeError was thrown while handling a gesture:
type 'List' is not a subtype of type 'List'
The page just on captures the data sent from the code above and display the image.
please if anyone know why is the error and help me .

Change the images to List<Object> images = [].

Related

This is the latest dialogflow flutter... I dont get response from Dialogflow. I get this Error " The method '[]' was called on null."

import 'package:bubble/bubble.dart';
import 'package:dialogflow_flutter/dialogflowFlutter.dart';
import 'package:dialogflow_flutter/googleAuth.dart';
import 'package:dialogflow_flutter/language.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class ChatBotScreen extends StatefulWidget {
const ChatBotScreen({Key? key}) : super(key: key);
#override
_ChatBotScreenState createState() => _ChatBotScreenState();
}
class _ChatBotScreenState extends State<ChatBotScreen> {
///Dialogflow
void response(query) async {
AuthGoogle authGoogle = await AuthGoogle(fileJson: "assets/services.json").build();
DialogFlow dialogflow = DialogFlow(authGoogle: authGoogle, language: Language.english);
AIResponse aiResponse = await dialogflow.detectIntent(query);
setState(() {
messages.insert(0, {"data": 0, "message":
aiResponse.getListMessage()![0]["text"]["text"][0].toString()
}
);
}
);
}
final messageInsert = TextEditingController();
///list where needed fixing i guess
List<Map> messages = [];
#override
Widget build(BuildContext context) {
return Scaffold(backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Colors.black87,
centerTitle: false,
toolbarHeight: 100,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(30),
bottomRight: Radius.circular(30),
),
),
elevation: 10,
title: const Text("LAIRA",
style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Lato',
fontSize: 24,
),
),
),
body: Column(
children: <Widget>[
Flexible(
///listview builder
child: ListView.builder(
reverse: true,
itemCount: messages.length,
itemBuilder: (context, index) => chat(
messages[index]["message"].toString(),
messages[index]["data"]
)
)
),
///divider
const Divider(
color: Colors.white,
height: 6.0,
),
Container(
padding: const EdgeInsets.only(left: 15.0, right: 15.0, bottom: 10, top: 10),
///Textfield
margin: const EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
children: [
Flexible(
child: TextField(
controller: messageInsert,
decoration: InputDecoration(
fillColor: Colors.grey[200],
contentPadding:
const EdgeInsets.symmetric(horizontal: 25, vertical: 20),
filled: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.none,
),
),
hintText: "Type your message...",
hintStyle: const TextStyle(
fontFamily: 'Lato',
fontSize: 18.0)),
)
),
///onpressed send
Container(
margin: const EdgeInsets.symmetric(horizontal: 4.0),
child: IconButton(
icon: const Icon(
Icons.send,
size: 30.0,
),
onPressed: () {
if (messageInsert.text.isEmpty) {
if (kDebugMode) {
print("empty message");
}
} else {
setState(() {
messages.insert(0, {"data": 1, "message": messageInsert.text});
});
response(messageInsert.text);
messageInsert.clear();
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
}
}
),
)
],
),
),
const SizedBox(
height: 15.0,
)
],
),
);
}
///chat system
Widget chat(String message, int data) {
return Padding(
padding: const EdgeInsets.all(10.0),
child: Bubble(
radius: const Radius.circular(10.0),
color: data == 0 ? Colors.blue : Colors.black87,
elevation: 5,
alignment: data == 0 ? Alignment.topLeft : Alignment.topRight,
nip: data == 0 ? BubbleNip.leftBottom : BubbleNip.rightTop,
child: Padding(
padding: const EdgeInsets.all(7.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
// CircleAvatar(
// backgroundImage: AssetImage(
// data == 0 ? "assets/bot.png" : "assets/user.png"),
// ),
const SizedBox(
width: 10.0,
),
Flexible(
child: Text(
message,
style: const TextStyle(
color: Colors.white,
fontSize: 19,
fontFamily: 'Lato'
),
)
)
],
),
)
),
);
}
}

How to solve this error? 'List<Word?>' is not a subtype of type 'List<Word>' of 'val'E/flutter (29035): #0 RxObjectMixin.value=

I have defined a variable named data in the Controller class. I am getting the error I mentioned above in the fillWordlist method. I created listview.builder in the historyWordList method in the view class. but the list does not appear on the screen and I am getting this error. 'List<Word?>' is not a subtype of type 'List' of 'val'E/flutter (29035): #0 RxObjectMixin.value= (package:get/get_rx/src/rx_types/rx_core/rx_impl .darts)
E/flutter (29035): #1 WordController.fillWordList (package:your_research_translation/controller/word_controller.dart:56:10)'
Controller.class
class WordController extends GetxController {
TextEditingController controllerInput1 = TextEditingController();
TextEditingController controllerInput2 = TextEditingController();
RxBool active2 = false.obs;
final translator = GoogleTranslator();
RxList data = <Word>[].obs;
#override
void onInit() {
fillWordList();
super.onInit();
}
onClickIconButtonFavori() {
if (controllerInput1.text.isNotEmpty && controllerInput2.text.isNotEmpty) {
addNote();
clear();
}
}
showText() {
if (active2.value == true) {
return;
}
active2.toggle();
}
ekle(Word word) async {
var val = await WordRepo().add(word);
showDilog("Kayıt Başarılı");
update();
return val;
}
updateWord(Word word) async {
var val = await WordRepo().update(word);
showDilog("Kayıt Başarılı");
return val;
}
deleteWord(int? id) async {
var val = await WordRepo().deleteById(id!);
return val;
}
fillWordList() async {
data.value = await WordRepo().getAll();
}
translateLanguage(String newValue) async {
if (newValue == null || newValue.length == 0) {
return;
}
List list = ["I", "i"];
if (newValue.length == 1 && !list.contains(newValue)) {
return;
}
var translate = await translator.translate(newValue, from: 'en', to: 'tr');
controllerInput2.text = translate.toString();
return translate;
}
showDilog(String message) {
Get.defaultDialog(title: "Bilgi", middleText: message);
}
addNote() async {
var word =
Word(wordEn: controllerInput1.text, wordTr: controllerInput2.text);
await ekle(word);
fillWordList();
}
clear() {
controllerInput2.clear();
controllerInput1.clear();
}
updateNote() async {
var word =
Word(wordEn: controllerInput1.text, wordTr: controllerInput2.text);
await updateWord(word);
await fillWordList();
update();
}
}
view class: Main_page.dart
class MainPage extends StatelessWidget {
String _firstLanguage = "English";
String _secondLanguage = "Turkish";
WordController controller = Get.put(WordController());
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: _drawer,
backgroundColor: Colors.grey.shade300,
appBar: _appbar,
body: _bodyScaffold,
floatingActionButton: _floattingActionButton,
);
}
SingleChildScrollView get _bodyScaffold {
return SingleChildScrollView(
child: Column(
children: [
chooseLanguage,
translateTextView,
//futureBuilder,
],
),
);
}
AppBar get _appbar {
return AppBar(
backgroundColor: Colors.blueAccent,
centerTitle: true,
title: Text("TRANSLATE"),
elevation: 0.0,
);
}
get chooseLanguage => Container(
height: Get.height / 12.0,
decoration: buildBoxDecoration,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
firstChooseLanguage,
changeLanguageButton,
secondChooseLanguage,
],
),
);
get buildBoxDecoration {
return BoxDecoration(
color: Colors.white,
border: Border(
bottom: BorderSide(
width: 3.5,
color: Colors.grey,
),
),
);
}
get translateTextView => Column(
children: [
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
),
margin: EdgeInsets.only(left: 2.0, right: 2.0, top: 2.0),
child: _formTextField,
),
Obx(
() => Container(
height: controller.active2 == true
? Get.height / 2.3
: Get.height / 1.6,
child: historyWordList,
),
)
],
);
Widget get historyWordList {
return ListView.builder(
itemCount: controller.data.length,
itemBuilder: (context, index) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
),
margin: EdgeInsets.only(left: 8.0, right: 8.0, top: 0.8),
child: Container(
color: Colors.white30,
padding: EdgeInsets.only(left: 8.0, top: 8.0, bottom: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Obx(()=>Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
firstText(controller.data[index].value),
secondText(controller.data[index].value),
],
)),
historyIconbutton,
],
),
),
);
},
);
}
get _formTextField {
return Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
color: Colors.white30,
height: Get.height / 6.0,
padding: EdgeInsets.only(left: 16.0, top: 8.0, bottom: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
textFormFieldEntr, //one textfield
favoriIconButton,
],
),
),
textFormField, //burası kapandı // second
],
),
);
}
get textFormFieldEntr {
return Flexible(
child: Container(
height: Get.height / 5.2,
child: TextFormField(
readOnly: true, //sadece okuma
onTap: () {
showMaterialBanner();
},
controller: controller.controllerInput1,
onChanged: (text) {
if (text.isEmpty) {
controller.active2(false);
} else {
controller.active2(true);
}
},
maxLines: 6,
decoration: InputDecoration(
hintText: "Enter",
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
),
);
}
void showMaterialBanner() {
ScaffoldMessenger.of(Get.context!).showMaterialBanner(MaterialBanner(
backgroundColor: Colors.white,
content: Padding(
padding: const EdgeInsets.only(top: 40.0),
child: Column(
children: [
TextFormField(
controller: controller.controllerInput1,
maxLines: 7,
onChanged: (text) {
controller.translateLanguage(text);
if (text.isNotEmpty) {
controller.showText();
}
// controller.showText();
},
decoration: InputDecoration(
suffixIcon: IconButton(
onPressed: () {
if (controller.controllerInput1.text.length > 0) {
controller.clear();
} else {
controller.clear();
closeBanner();
}
},
icon: Icon(Icons.clear),
),
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
SizedBox(height: Get.height / 6.0),
TextFormField(
controller: controller.controllerInput2,
maxLines: 7,
onTap: () {
if (controller.controllerInput1.text.isEmpty) {
controller.clear();
} else {
controller.addNote();
}
closeBanner();
},
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
],
),
),
actions: [
IconButton(
onPressed: () {
closeBanner();
},
icon: Icon(null),
),
]));
}
void closeBanner() {
ScaffoldMessenger.of(Get.context!).hideCurrentMaterialBanner();
}
get textFormField {
return Obx(() {
return Container(
child: Visibility(
visible: controller.active2.value, //false
child: Container(
color: Colors.white30,
height: Get.height / 5.2,
padding:
EdgeInsets.only(left: 16.0, right: 42.0, top: 8.0, bottom: 8.0),
child: TextFormField(
readOnly: true,
controller: controller.controllerInput2,
maxLines: 6,
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
),
),
);
});
}
IconButton get historyIconbutton {
return IconButton(
onPressed: () {},
icon: Icon(Icons.history),
iconSize: 30.0,
);
}
Text firstText(Word word) {
return Text(
"İngilizce: ${word.wordEn ?? ""}",
style: TextStyle(
fontWeight: FontWeight.w600,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
get changeLanguageButton {
return Material(
color: Colors.white,
child: IconButton(
icon: Icon(
Icons.wifi_protected_setup_rounded,
color: Colors.indigo,
size: 30.0,
),
onPressed: () {},
),
);
}
get secondChooseLanguage {
return Expanded(
child: Material(
color: Colors.white,
child: InkWell(
onTap: () {},
child: Center(
child: Text(
this._secondLanguage,
style: TextStyle(
color: Colors.blue[600],
fontSize: 22.0,
),
),
),
),
),
);
}
get firstChooseLanguage {
return Expanded(
child: Material(
color: Colors.white,
child: InkWell(
onTap: () {},
child: Center(
child: Text(
this._firstLanguage,
style: TextStyle(
color: Colors.blue[600],
fontSize: 22.0,
),
),
),
),
),
);
}
Text secondText(Word word) {
return Text(
"Türkçe: ${word.wordTr ?? ""}",
style: TextStyle(
fontWeight: FontWeight.w400,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
get favoriIconButton {
return IconButton(
alignment: Alignment.topRight,
onPressed: controller.onClickIconButtonFavori,
icon: Icon(
Icons.forward,
color: Colors.blueAccent,
size: 28.0,
),
);
}
FloatingActionButton get _floattingActionButton {
return FloatingActionButton(
onPressed: () {
Get.to(WordListPage());
},
child: Icon(
Icons.app_registration,
size: 30,
),
);
}
Drawer get _drawer {
return Drawer(
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: <Widget>[
userAccountsDrawerHeader,
drawerFavorilerim,
drawersettings,
drawerContacts,
],
),
);
}
ListTile get drawerContacts {
return ListTile(
leading: Icon(Icons.contacts),
title: Text("Contact Us"),
onTap: () {
Get.back();
},
);
}
ListTile get drawersettings {
return ListTile(
leading: Icon(Icons.settings),
title: Text("Settings"),
onTap: () {
Get.back();
},
);
}
ListTile get drawerFavorilerim {
return ListTile(
leading: Icon(
Icons.star,
color: Colors.yellow,
),
title: Text("Favorilerim"),
onTap: () {
Get.to(FavoriListPage());
},
);
}
UserAccountsDrawerHeader get userAccountsDrawerHeader {
return UserAccountsDrawerHeader(
accountName: Text("UserName"),
accountEmail: Text("E-mail"),
currentAccountPicture: CircleAvatar(
backgroundColor: Colors.grey,
child: Text(
"",
style: TextStyle(fontSize: 40.0),
),
),
);
}
}
This error is due to null safety. Try adding ! after every instance of word which you are passing in the function

Flutter Firebase where query arrayContains in List [duplicate]

This question already has answers here:
Firestore search array contains for multiple values
(6 answers)
Closed 1 year ago.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class SearchPage extends StatefulWidget {
#override
_SearchPageState createState() => _SearchPageState();
}
class _SearchPageState extends State<SearchPage> with TickerProviderStateMixin {
final searchController = TextEditingController();
final _firestore = FirebaseFirestore.instance;
static const defaultSearch = "";
String search = defaultSearch ;
void dispose() {
searchController.dispose();
super.dispose();
}
#override
void initState() {
super.initState();
searchController.addListener(searchChanged);
}
searchChanged() {
setState(() {
search = searchController.text;
});
}
#override
Widget build(BuildContext context) {
var tarifRef = _firestore
.collection("vehicles")
.where("models", arrayContains: search);
return Scaffold(
body: Container(
child: ListView(
children: <Widget>[
Expanded(
child: Container(
height: MediaQuery.of(context).size.height * 0.08,
margin: EdgeInsets.only(top: 25),
child: Text(
"Vehicles",
style: TextStyle(
fontSize: 20, fontFamily: "Quando", color: Colors.indigo),
),
),
),
Expanded(
child: Container(
margin: EdgeInsets.only(
top: 10.0, bottom: 10.0, right: 30, left: 30),
child: TextField(
keyboardType: TextInputType.text,
decoration: InputDecoration(
prefixIcon: Icon(Icons.search),
),
controller: searchController,
),
),
),
Expanded(
child: Container(
height: MediaQuery.of(context).size.height * 0.50,
child: StreamBuilder<QuerySnapshot>(
stream: tarifRef.snapshots(),
builder: (BuildContext context, AsyncSnapshot asyncsnapshot) {
if (asyncsnapshot.hasError) {
return Center(
child: Text("Error"),
);
} else {
if (asyncsnapshot.hasData) {
List<DocumentSnapshot> listOfDocumentSnapshot =
asyncsnapshot.data.docs;
return Flexible(
child: ListView.builder(
itemCount: listOfDocumentSnapshot.length,
itemBuilder: (context, index) {
return Card(
color: Colors.indigo,
child: ListTile(
title: Text(
"${listOfDocumentSnapshot[index]["name"]}",
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
subtitle: Text(
"${listOfDocumentSnapshot[index]["models"]}",
style: TextStyle(
fontSize: 15,
color: Colors.white,
),
),
trailing: IconButton(
icon: Icon(
Icons.delete,
color: Colors.white,
),
onPressed: () async {
await listOfDocumentSnapshot[index]
.reference
.delete();
},
),
),
);
},
),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
}
},
),
),
),
],
),
),
);
}
}
This my all code and also I have database in Firebase like this;
vehicles: [
{
"name": "Vehicle1",
"models": ["bus", "plane", "motorcycle"]
},
{
"name": "Vehicle2",
"models": ["motorcycle", "sporcar", "plane"]
},
{
"name": "Vehicle3",
"models": ["motorcycle", "plane", "bus"]
}
]
In this example I can take one input from user, I can query and display which list includes this data but I want to query more than one data is in lists or not.
For example in this code if user input bus, program display Vehicle1 list but I want user can input more than one data such as plane and motorcycle. And so when the user input the plane and motorcycle, I want it to be displayed the list of Vehicle 2 and Vehicle 3.
I try a lot of different ways but I can't found proparly solution to this problem.
I think you're looking for arrayContainsAny here:
var tarifRef = _firestore
.collection("vehicles")
.where("models", arrayContainsAny: ["bus", "plane"]);
This query will return documents whose models array contains either "bus", "plane" or both.
Also see the FlutterFire documentation for Query.where.

Building a List<FlatButton> using Firebase [duplicate]

This question already has answers here:
how to assign future<> to widget in flutter?
(6 answers)
Closed 1 year ago.
I'm building a list of buttons, using Firebase to name each one, but my code presents this error when referencing "_getButtonBar" to the Widget: "The argument type 'Future<List>' can't be assigned to the parameter type 'List'". Should the widget be Future too? Does anyone know what's missing?
class ThemesList extends StatelessWidget {
Future<List<FlatButton>> _getButtonBar(context) async {
List<FlatButton> _list1 = [];
tot = await callReadTotal(); //Receives length to make the loop.
getListCauses(); //Calls Firebase to use arrCauses = List () for child: Text
for (int i = 1; i <= tot; i++) {
_list1.add(
FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
side: BorderSide(color: Color.fromRGBO(150, 1, 1, 1)),
),
splashColor: Color.fromRGBO(150, 1, 1, 1),
onPressed: () => {
setChoice(i),
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CausesList()),
),
},
child: Text(
arrCauses[i],
style: TextStyle(
color: Color.fromRGBO(150, 1, 1, 1),
fontSize: 20,
fontFamily: 'Balsamiq_Sans',
),
),
),
);
}
return _list1;
}
#override
Widget build(BuildContext context) {
return Platform.isIOS
? CupertinoPageScaffold(child: null)
: Scaffold(
appBar: AppBar(
title: Text(
'ICare',
style: TextStyle(
color: Color.fromRGBO(150, 1, 1, 1),
fontSize: 40,
fontFamily: 'Balsamiq_Sans',
fontWeight: FontWeight.w500,
),
),
flexibleSpace: Image(
image: AssetImage('assets/images/solidariedade.png'),
color: Color.fromRGBO(255, 200, 200, 0.45),
colorBlendMode: BlendMode.modulate,
fit: BoxFit.cover,
),
),
body: Stack(
children: <Widget>[
Container(
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: ButtonBar(
children: _getButtonBar(
context), //<-- Here it points out the error.
alignment: MainAxisAlignment.center,
),
),
),
],
),
);
}
}
Your problem can be solve via two options.
By using StatefulWidget
import 'package:flutter/material.dart';
class ThemesList extends StatefulWidget {
#override
_ThemesListState createState() => _ThemesListState();
}
class _ThemesListState extends State<ThemesList> {
List<FlatButton> _buttonBar = [];
#override
void initState() {
_getButtonBar();
super.initState();
}
_getButtonBar() async {
List<FlatButton> _list1 = [];
tot = await callReadTotal(); //Receives length to make the loop.
getListCauses(); //Calls Firebase to use arrCauses = List () for child: Text
for (int i = 1; i <= tot; i++) {
_list1.add(
FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
side: BorderSide(color: Color.fromRGBO(150, 1, 1, 1)),
),
splashColor: Color.fromRGBO(150, 1, 1, 1),
onPressed: () => {
setChoice(i),
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CausesList()),
),
},
child: Text(
arrCauses[i],
style: TextStyle(
color: Color.fromRGBO(150, 1, 1, 1),
fontSize: 20,
fontFamily: 'Balsamiq_Sans',
),
),
),
);
}
_buttonBar = _list1;
setState(() {});
}
#override
Widget build(BuildContext context) {
return Platform.isIOS
? CupertinoPageScaffold(child: null)
: Scaffold(
appBar: AppBar(
title: Text(
'ICare',
style: TextStyle(
color: Color.fromRGBO(150, 1, 1, 1),
fontSize: 40,
fontFamily: 'Balsamiq_Sans',
fontWeight: FontWeight.w500,
),
),
flexibleSpace: Image(
image: AssetImage('assets/images/solidariedade.png'),
color: Color.fromRGBO(255, 200, 200, 0.45),
colorBlendMode: BlendMode.modulate,
fit: BoxFit.cover,
),
),
body: Stack(
children: <Widget>[
Container(
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: ButtonBar(
children: _buttonBar,
alignment: MainAxisAlignment.center,
),
),
),
],
),
);
}
}
By using FutureBuilder
import 'package:flutter/material.dart';
class ThemesList extends StatelessWidget {
Future<List<FlatButton>> _getButtonBar(context) async {
List<FlatButton> _list1 = [];
tot = await callReadTotal(); //Receives length to make the loop.
getListCauses(); //Calls Firebase to use arrCauses = List () for child: Text
for (int i = 1; i <= tot; i++) {
_list1.add(
FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
side: BorderSide(color: Color.fromRGBO(150, 1, 1, 1)),
),
splashColor: Color.fromRGBO(150, 1, 1, 1),
onPressed: () => {
setChoice(i),
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CausesList()),
),
},
child: Text(
arrCauses[i],
style: TextStyle(
color: Color.fromRGBO(150, 1, 1, 1),
fontSize: 20,
fontFamily: 'Balsamiq_Sans',
),
),
),
);
}
return _list1;
}
#override
Widget build(BuildContext context) {
return Platform.isIOS
? CupertinoPageScaffold(child: null)
: Scaffold(
appBar: AppBar(
title: Text(
'ICare',
style: TextStyle(
color: Color.fromRGBO(150, 1, 1, 1),
fontSize: 40,
fontFamily: 'Balsamiq_Sans',
fontWeight: FontWeight.w500,
),
),
flexibleSpace: Image(
image: AssetImage('assets/images/solidariedade.png'),
color: Color.fromRGBO(255, 200, 200, 0.45),
colorBlendMode: BlendMode.modulate,
fit: BoxFit.cover,
),
),
body: Stack(
children: <Widget>[
Container(
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: FutureBuilder<List<FlatButton>>(
future: _getButtonBar(context),
builder: (context,
AsyncSnapshot<List<FlatButton>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading....');
break;
default:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
else
return ButtonBar(
children: snapshot.data,
alignment: MainAxisAlignment.center,
);
}
}),
),
),
],
),
);
}
}

Use Arrows to Navigate through list / change Widget

I am currently struggling to implement a "list" with two QR-Codes.
I want to change the shown QR code by pressing the arrows left and right to it.
"list" because currently I don't use a list view.
Currently it looks like this: Current App
The QR codes are within a ModalBottomSheet.
Here is my code so far:
void _onButtonPressed() {
bool inAppQr = true;
String _output = "QR 1";
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
context: context,
builder: (context) {
return Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
_output,
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 15.0),
),
SizedBox(
height: 30,
),
SizedBox(
height: 5,
width: 150,
child: LinearProgressIndicator(
backgroundColor: Colors.white,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.blueGrey,
),
),
),
SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
setState(() {
inAppQr = false;
_output = "QR 1";
});
}),
inAppQr == true
? PrettyQr(
typeNumber: 3,
size: 150,
data: 'Test',
errorCorrectLevel: QrErrorCorrectLevel.M,
roundEdges: true)
: PrettyQr(
typeNumber: 3,
size: 150,
data: 'Test 2',
errorCorrectLevel: QrErrorCorrectLevel.M,
roundEdges: true),
IconButton(
icon: Icon(Icons.arrow_forward_ios),
onPressed: () {
setState(() {
_output = "QR 2";
inAppQr = true;
});
}),
],
),
]),
);
});
}
Thanks for your help!
Solution found thanks to Zeeshan Hussain!
I added a StatefulBuilder with the StateSetter newState
This code worked for me:
void _onButtonPressed() {
bool inAppQr = true;
String _output = "QR 1";
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
context: context,
builder: (context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter newState) {
return Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
_output,
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 15.0),
),
SizedBox(
height: 30,
),
SizedBox(
height: 5,
width: 150,
child: LinearProgressIndicator(
backgroundColor: Colors.white,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.blueGrey,
),
),
),
SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
newState(() {
inAppQr = true;
_output = "QR 1";
});
}),
inAppQr == true
? PrettyQr(
typeNumber: 3,
size: 150,
data: 'Test',
errorCorrectLevel: QrErrorCorrectLevel.M,
roundEdges: true)
: PrettyQr(
typeNumber: 3,
size: 150,
data: 'Test 2',
errorCorrectLevel: QrErrorCorrectLevel.M,
roundEdges: true),
IconButton(
icon: Icon(Icons.arrow_forward_ios),
onPressed: () {
newState(() {
_output = "QR 2";
inAppQr = false;
});
}),
],
),
]),
);
},
);
});