How to call a method from another class in flutter - android

I'm Beginner to coding. I have created a Image picker in flutter, I want to use the image picker in many different pages, so I have created a separate class, but when I call the method in other pages, it just open the gallery but,it is not picking the image from gallery and displaying the picked image.There is no any error.
Kindly, help to solve the issue.
Thanks in advance
My Code:
main.dart:
import 'package:flutter/material.dart';
import 'package:project1test/healthscreen_expat.dart';
import 'package:project1test/forms/parkings.dart';
class accomodationform extends StatefulWidget {
String text;
accomodationform(String name) {
text = name;
}
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return MyAppState(text);
}
}
class MyAppState extends State<accomodationform> {
Mod1 mod11 = new Mod1();
String labels;
MyAppState([String label]) {
labels = label;
}
Image1 im = Image1();
final scaffoldkey = new GlobalKey<ScaffoldState>();
final formkey = new GlobalKey<FormState>();
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: new Padding(
padding: EdgeInsets.only(left: 20.0, right: 20.0, top: 20),
child: new Form(
key: formkey,
child: ListView(children: <Widget>[
mod11.user(),
]))),
);
}
}
imagepick.dart
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class Mod1 {
var images1accom;
user() {
List<dynamic> img = List();
return Container(
margin: EdgeInsets.only(top: 20, right: 20, left: 20),
padding: EdgeInsets.only(top: 20.0),
width: double.infinity,
height: 150.0,
color: Colors.white70,
child: Center(
child: Row(
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlineButton(
onPressed: () async {
images1accom =
await ImagePicker.pickImage(source: ImageSource.gallery);
img.add(images1accom);
},
child: Row(children: <Widget>[
Icon(Icons.camera_alt),
Text(
"Choose File",
style: TextStyle(fontSize: 12.0),
textAlign: TextAlign.end,
)
]),
borderSide: BorderSide(color: Colors.pink),
textColor: Colors.pinkAccent,
padding: EdgeInsets.all(10.0),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
)),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
),
),
],
),
),
);
}
}

Well, I think maybe it would be good for you to study object-oriented programming, dart, and how Flutter works.
Initially, I need to tell you that you simply cannot do what you are trying to do, insert widgets within classes, with separate functions, and try to instantiate it within a Stateful.
Widgets must not be instantiated, and if you want to componentize something, you must do it using a stateful or stateless class, not an ordinary class.
Your Mod class should look like this:
class ChoosePic extends StatefulWidget {
ChoosePic({Key key}) : super(key: key);
#override
_ChoosePicState createState() => _ChoosePicState();
}
class _ChoosePicState extends State<ChoosePic> {
List<dynamic> img = List();
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 20, right: 20, left: 20),
padding: EdgeInsets.only(top: 20.0),
width: double.infinity,
height: 150.0,
color: Colors.white70,
child: Center(
child: Row(
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlineButton(
onPressed: () async {
File images1accom =
await ImagePicker.pickImage(source: ImageSource.gallery);
img.add(images1accom);
setState(() {});
},
child: Row(children: <Widget>[
Icon(Icons.camera_alt),
Text(
"Choose File",
style: TextStyle(fontSize: 12.0),
textAlign: TextAlign.end,
)
]),
borderSide: BorderSide(color: Colors.pink),
textColor: Colors.pinkAccent,
padding: EdgeInsets.all(10.0),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
)),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
),
),
],
),
),
);
}
}
And you can to use it with
child: ChoosePic()
I have no idea why you are using a listview in your main class, but if it is really necessary, you would do this:
ListView(children: <Widget>[
ChoosePic(),
])
If you want the value of img, you will need a state manager for this:
Using Get (add this package to pubspec):
https://pub.dev/packages/get
Create class with shared state:
class Controller extends GetController {
static Controller get to => Get.find();
List<dynamic> img = List();
takeImage() {
File images1accom =
await ImagePicker.pickImage(source: ImageSource.gallery);
img.add(images1accom);
update(this);
}
}
// use it:
class ChoosePic extends StatefulWidget {
ChoosePic({Key key}) : super(key: key);
#override
_ChoosePicState createState() => _ChoosePicState();
}
class _ChoosePicState extends State<ChoosePic> {
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 20, right: 20, left: 20),
padding: EdgeInsets.only(top: 20.0),
width: double.infinity,
height: 150.0,
color: Colors.white70,
child: Center(
child: Row(
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlineButton(
onPressed: () async {
Controller.to.takeImage();
},
child: Row(children: <Widget>[
Icon(Icons.camera_alt),
Text(
"Choose File",
style: TextStyle(fontSize: 12.0),
textAlign: TextAlign.end,
)
]),
borderSide: BorderSide(color: Colors.pink),
textColor: Colors.pinkAccent,
padding: EdgeInsets.all(10.0),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
)),
Expanded(
child: GetBuilder<Controller>(
init: Controller(),
builder: (controller) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: controller.img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
controller.img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
);
}
),
),
],
),
),
);
}
}
Now you can get the image list from anywhere in your code with:
on widget three controller.img;
GetBuilder<Controller>(
init: Controller(),
builder: (controller) {
Example:
GetBuilder<Controller>(
init: Controller(),
builder: (controller) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: controller.img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
controller.img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
);
And take it out of the widget tree with:
Controller.to.img
Note: init: Controller() can only be used once, if you need GetBuilder elsewhere, don't use it. Use, for example:
GetBuilder<Controller>(
builder: (controller) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: controller.img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
controller.img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
);
Well, I shouldn't answer that, as it qualifies as a general question, but since you are a beginner, I answered to help you, in detail. I hope you understand the basics soon, and become a great developer someday.
Welcome to Flutter!

You need to create a separate widget for Mod1 class.
MyAppState
Widget build(BuildContext context) {
return Scaffold(
body: new Padding(
padding: EdgeInsets.only(left: 20.0, right: 20.0, top: 20),
child: new Form(key: formkey, child: Mod1())),
);
}
Mod1 widget
class Mod1 extends StatefulWidget {
#override
State<StatefulWidget> createState() => Mod1State();
}
class Mod1State extends State<Mod1> {
var images1accom;
List<dynamic> img = List();
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 20, right: 20, left: 20),
padding: EdgeInsets.only(top: 20.0),
width: double.infinity,
height: 150.0,
color: Colors.white70,
child: Center(
child: Row(
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlineButton(
onPressed: () async {
images1accom =
await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
img.add(images1accom);
});
},
child: Row(children: <Widget>[
Icon(Icons.camera_alt),
Text(
"Choose File",
style: TextStyle(fontSize: 12.0),
textAlign: TextAlign.end,
)
]),
borderSide: BorderSide(color: Colors.pink),
textColor: Colors.pinkAccent,
padding: EdgeInsets.all(10.0),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
)),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
),
),
],
),
),
);
}
}

if you want to use a method in different pages you can use Providers

Related

How to use Streambuilder in flutter

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
//Run this first
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Smart Bin',
home: new HomePageWidget(),
);
}
}
class HomePageWidget extends StatefulWidget {
const HomePageWidget({Key key}) : super(key: key);
#override
_HomePageWidgetState createState() => _HomePageWidgetState();
}
class _HomePageWidgetState extends State<HomePageWidget> {
final scaffoldKey = GlobalKey<ScaffoldState>();
final currentBinRecord = FirebaseFirestore.instance.collection("current_bin");
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
appBar: AppBar(
title: Text(
'SmartBin',
),
),
body: SafeArea(
child: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Expanded(
child: StreamBuilder<List<CurrentBinRecord>>(
stream: queryCurrentBinRecord(
queryBuilder: (currentBinRecord) =>
currentBinRecord.orderBy('level', descending: true),
),
builder: (context, snapshot) {
// Customize what your widget looks like when it's loading.
if (!snapshot.hasData) {
return Center(
child: SizedBox(
width: 50,
height: 50,
child: CircularProgressIndicator(),
),
);
}
List<CurrentBinRecord> listViewCurrentBinRecordList =
snapshot.data;
return ListView.builder(
padding: EdgeInsets.zero,
scrollDirection: Axis.vertical,
itemCount: listViewCurrentBinRecordList.length,
itemBuilder: (context, listViewIndex) {
final listViewCurrentBinRecord =
listViewCurrentBinRecordList[listViewIndex];
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
listViewCurrentBinRecord.area,
),
Text(
listViewCurrentBinRecord.level.toString(),
),
],
);
},
);
},
),
),
],
),
),
),
);
}
}
This is the error
First error is on:
child: StreamBuilder<List<CurrentBinRecord>>
The name 'CurrentBinRecord' isn't a type so it can't be used as a type argument.
Try correcting the name to an existing type, or defining a type named 'CurrentBinRecord'.
Second error is on:
stream: queryCurrentBinRecord
The method 'queryCurrentBinRecord' isn't defined for the type '_HomePageWidgetState'.
Try correcting the name to the name of an existing method, or defining a method named 'queryCurrentBinRecord'.
Third error is on:
List<CurrentBinRecord> listViewCurrentBinRecordList =
snapshot.data;
The name 'CurrentBinRecord' isn't a type so it can't be used as a type argument.
Try correcting the name to an existing type, or defining a type named 'CurrentBinRecord'.
These is the syntax try -
return StreamBuilder(
stream: theStreamSource, // Eg a firebase query
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, int index) {
return Text(snapshot.data.documents[index]['title']);
}
);
},
);
Hope it helps.
I think the best way to use StreamBuilder is to create separate controller class that can handle all your business logic and update UI.
// your widget class
class UIClass extends StatefulWidget {
const UIClass({Key key}) : super(key: key);
#override
_UIClassState createState() => _UIClassState();
}
class _UIClassState extends State<UIClass> {
UIClassController<List<CurrentBinRecord>> _uiController;
#override
void initState() {
_uiController = UIClassController(StreamController<List<CurrentBinRecord>>());
super.initState();
}
#override
Widget build(BuildContext context) {
return Column(
children: [
Text("Hello Everyone"),
StreamBuilder<List<CurrentBinRecord>>(
stream: _uiController.uiStream,
builder: (context, snapshot) {
if(snapshot.hasError){
return ErrorWidget();
}
else if(snapshot.connectionState == ConnectionState.waiting){
return WaitingWidget();
}
else if(snapshot.hasData){
return ListView.builder(
padding: EdgeInsets.zero,
scrollDirection: Axis.vertical,
itemCount: snapshot.data.length,
itemBuilder: (context, listViewIndex) {
final listViewCurrentBinRecord =
snapshot.data[listViewIndex];
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
listViewCurrentBinRecord.area,
),
Text(
listViewCurrentBinRecord.level.toString(),
),
],
);
},
);
}
else{
return SizedBox();
}
}
),
],
);
}
#override
void dispose() {
super.dispose();
_uiController.dispose();
}
}
// controller class to handle all business logic
// you can also split it into multiple sub controllers
class UIClassController<T> {
final StreamController<T> _controller;
// If you are using this on multiple widgets then use asBroadcastStream()
Stream<T> get uiStream => _controller.stream;
UIClassController(this._controller);
void updateMyUI([dynamic params]){
T t;
// your logic //
//------------//
_controller.sink.add(t);
}
void dispose(){
_controller.close();
}
}
Code I'm Using for StreamBuilder
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import '../door/widgets/Navbar.dart';
import '../door/widgets/sidenav.dart';
import 'package:get/get.dart';
FirebaseAuth auth = FirebaseAuth.instance;
class CartPage extends StatefulWidget {
#override
_CartPageState createState() => _CartPageState();
}
class _CartPageState extends State<CartPage> {
final FirebaseFirestore fb = FirebaseFirestore.instance;
int up = 1;
bool loading = false;
final ScrollController _scrollController = ScrollController();
#override
void initState() {
super.initState();
getCartData();
}
void addMore(qty, documentID) {
int new_qty = qty + 1;
Get.snackbar('Qty! ', new_qty.toString());
String collection_name = "cart_${auth.currentUser?.email}";
FirebaseFirestore.instance
.collection(collection_name)
.doc(documentID)
.update({
'qty': new_qty,
'updated_at': Timestamp.now(),
}) // <-- Your data
.then((_) => print('Added'))
.catchError((error) => Get.snackbar('Failed!', 'Error: $error'));
}
void minusMore(qty, documentID) {
if (qty > 1) {
int new_qty = qty - 1;
String collection_name = "cart_${auth.currentUser?.email}";
FirebaseFirestore.instance
.collection(collection_name)
.doc(documentID)
.update({
'qty': new_qty,
'updated_at': Timestamp.now(),
}) // <-- Your data
.then((_) => print('Subtracted'))
.catchError((error) => Get.snackbar('Failed!', 'Error: $error'));
}
}
Stream<QuerySnapshot> getCartData() {
String collection_name = "cart_${auth.currentUser?.email}";
return FirebaseFirestore.instance
.collection(collection_name)
.orderBy("created_at", descending: false)
.snapshots();
}
final ButtonStyle style = ElevatedButton.styleFrom(
minimumSize: Size(50, 30),
backgroundColor: Color(0xFFFFB61A),
elevation: 6,
textStyle: const TextStyle(fontSize: 11),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20),
)));
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: Navbar.navbar(),
drawer: Sidenav.sidenav(),
body: Container(
padding: EdgeInsets.all(10.0),
child: StreamBuilder<QuerySnapshot>(
stream: getCartData(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError) {
return buildText('Something Went Wrong Try later');
} else {
if (!snapshot.hasData) {
return Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 100,
minHeight: 190,
maxWidth: 200,
maxHeight: 200,
),
child: Icon(Icons.shopping_cart, size: 45),
),
title: Text('No Food!'),
subtitle: const Text('Your cart is empty!'),
),
],
),
);
} else {
return ListView.builder(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
itemCount: snapshot.data?.docs.length,
itemBuilder: (BuildContext context, int index) {
return SizedBox(
height: 90.0,
child: Card(
elevation: 10,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
const SizedBox(
width: 20,
),
_buildImg('assets/logo.png', '60', '60'),
const SizedBox(
width: 14,
),
SizedBox(
width:
MediaQuery.of(context).size.width *
0.33,
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
const SizedBox(
height: 20,
),
Text(
snapshot.data?.docs[index]
["name"],
maxLines: 2,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14)),
const SizedBox(
height: 5,
),
Text(
"₹${snapshot.data?.docs[index]["price"]}",
style: const TextStyle(
fontWeight: FontWeight.w400,
fontSize: 12)),
],
),
),
const SizedBox(
width: 10,
),
Container(
margin: const EdgeInsets.only(
top: 20.0, bottom: 10.0),
decoration: BoxDecoration(
color: const Color(0xFFFFB61A),
// color: Color(0xFF0A2031),
borderRadius:
BorderRadius.circular(17)),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
crossAxisAlignment:
CrossAxisAlignment.end,
children: <Widget>[
SizedBox(
height: 40,
child: IconButton(
onPressed: () {
minusMore(
snapshot.data
?.docs[index]
["qty"],
snapshot
.data
?.docs[index]
.reference
.id);
},
color: Colors.white,
icon:
const Icon(Icons.remove)),
),
const SizedBox(
width: 5,
),
Container(
margin: const EdgeInsets.only(
bottom: 10.0),
child: Text(
"${snapshot.data?.docs[index]["qty"]}",
style: const TextStyle(
fontWeight:
FontWeight.w400,
color: Colors.white,
fontSize: 16)),
),
const SizedBox(
width: 5,
),
SizedBox(
height: 40,
child: IconButton(
color: Colors.white,
onPressed: () {
addMore(
snapshot.data
?.docs[index]
["qty"],
snapshot
.data
?.docs[index]
.reference
.id);
},
icon: const Icon(Icons.add)),
),
],
),
),
const SizedBox(
width: 10,
),
],
),
),
);
});
}
}
}
},
),
),
);
}
Widget buildText(String text) => Center(
child: Text(
text,
style: TextStyle(fontSize: 24, color: Colors.black),
),
);
_buildImg(img, hei, wid) {
return Container(
alignment: Alignment.center, // use aligment
child: Image.asset(
img,
height: double.parse(hei),
width: double.parse(wid),
fit: BoxFit.cover,
),
);
}
}

Flutter DragTarget onAccept is not being called

I am developing a feature where the user enters a sentence, in the next screen the words of that sentence get shuffled randomly, then the user has to drag the words to a drag target to form the original sentence.
You can get an idea from the screenshots below.
First screen
Second screen
Now the problem I am having is, when dragging the words to the target I can see the DragTarget is calling onWillAccept as I added a print() statement there, if it is doing so then it should call onAccept eventually but it is not doing so. This is why my codes that deal with Bloc are not getting called and the words are not showing up in the target spot.
Code
class SentenceMakeScreen extends StatefulWidget {
String inputSentence;
SentenceMakeScreen(this.inputSentence);
#override
State<SentenceMakeScreen> createState() => _SentenceMakeScreenState();
}
class _SentenceMakeScreenState extends State<SentenceMakeScreen> {
List<String> sentence = [];
List<Widget> wordWidgets = [];
bool isDragSuccessful = false;
final ButtonStyle _buttonStyle = ElevatedButton.styleFrom(
textStyle: TextStyle(fontSize: 20)
);
_getTextWidgets(List<String> sentence) {
for(var i = 0; i < sentence.length; i++){
wordWidgets.add(
Draggable<WordWidget>(
data: WordWidget(sentence[i]),
child: WordWidget(sentence[i]),
feedback: WordWidget(sentence[i]),
childWhenDragging: Container(),
)
);
}
}
_randomlyOrganizeSentence(String inputString) {
sentence = inputString.split(new RegExp(r" "));
sentence.shuffle();
print(sentence);
}
#override
void initState() {
// TODO: implement initState
_randomlyOrganizeSentence(widget.inputSentence);
_getTextWidgets(sentence);
super.initState();
}
#override
Widget build(BuildContext context) {
final _dragDropBloc = DragDropBloc();
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
},
),
),
body: Container(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
DragTarget<WordWidget>(
builder: (context, data, rejectedData) {
return Center(
child: this.isDragSuccessful
?
Container(
width: double.maxFinite,
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.white,
border: Border(
bottom: BorderSide(width: 1.0, color: Colors.black),
),
),
child: StreamBuilder<List<WordWidget>>(
stream: _dragDropBloc.widgetStream,
initialData: [],
builder: (BuildContext context, AsyncSnapshot<List<WordWidget>> snapshot) {
print("Here ${snapshot.data}");
return Wrap(
direction: Axis.horizontal,
children: [
//correctly ordered words
],
);
},
),
)
:
Container(
width: double.maxFinite,
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.white,
border: Border(
bottom: BorderSide(width: 1.0, color: Colors.black),
),
),
child: Text("Drag here")
),
);
},
onWillAccept: (data) {
print("true");
return true;
},
onAccept: (data) {
print(data.toString());
_dragDropBloc.dragDropEventSink.add(
DropEvent(WordWidget(data.toString()))
);
setState(() {
this.isDragSuccessful = true;
//draggedWords.add(data.toString());
});
},
),
Wrap(
direction: Axis.horizontal,
children: wordWidgets
),
Container(
child: ElevatedButton(
style: _buttonStyle,
onPressed: () {
},
child: Text("Check"),
),
),
],
),
),
);
}
}
WordWidget
import 'package:flutter/material.dart';
class WordWidget extends StatelessWidget {
final String word;
const WordWidget(this.word);
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.red[900],
border: Border.all(
width: 4,
color: Colors.black
),
borderRadius: BorderRadius.circular(10),
),
child: Padding(
padding: EdgeInsets.all(5),
child: Text(
word,
style: TextStyle(
color: Colors.white
),
)
),
);
}
}
I tried adding the type of data I am passing from Draggable to DragTarget, this is what was advised here. It did not work.
I was also getting the same error earlier today. I then upgraded my flutter to the latest version and wrote the DragTarget code again from scratch. I don't know what worked for me but you can try doing the same.

How to specify drag target for a certain widget Flutter (Single Draggable Being Dropped Into 3 Drag Targets Instead Of 1)

Here is the problem that I am facing:
I start off with a list of emoji's which I want to drop into these 3 Drop Targets
(I want to be able to select each emoji which goes into each of these drop targets)
When I drag one of these emojis (only one, which is in this case, the first one, it automatically drops into all the drag targets instead of only the first one).
This results in the same emoji populating all the drag targets unintentionally like this which is unexpected behavior:
My question is, how can I change my code so that I can make sure that, when I drag on emoji into the first, second, or third Drag target, only that respective drag target gets filled instead of all of them? Thanks a lot and I really appreciate your help!
Code For DragBox:
class DragBox extends StatefulWidget {
DragBox({this.animatedAsset, this.width});
final LottieBuilder animatedAsset;
final double width;
#override
_DragBoxState createState() => _DragBoxState();
}
class _DragBoxState extends State<DragBox> {
#override
Widget build(BuildContext context) {
return Draggable(
feedback: Container(
width: 50,
height: 50,
child: widget.animatedAsset,
),
child: Container(
child: widget.animatedAsset,
width: widget.width,
height: 50,
),
childWhenDragging: Container(),
data: widget.animatedAsset,
);
}
}
Code For Emoji Picker :
class AnimatedEmojiPicker extends StatefulWidget {
#override
_AnimatedEmojiPickerState createState() => _AnimatedEmojiPickerState();
}
class _AnimatedEmojiPickerState extends State<AnimatedEmojiPicker> {
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 10.0, right: 10.0),
child: Container(
width: MediaQuery.of(context).size.width,
height: 60,
decoration:
BoxDecoration(color: Colors.grey.shade400.withOpacity(0.5), borderRadius: BorderRadius.circular(20.0)),
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
Container(
width: 15,
),
DragBox(
animatedAsset: Lottie.asset('Assets/blushing.json'),
),
Container(
width: 15,
),
DragBox(
animatedAsset: Lottie.asset('Assets/cooldude.json'),
),
Container(
width: 15,
),
DragBox(
animatedAsset: Lottie.asset('Assets/zipmouth.json'),
),
//More drag boxes like this one
],
),
),
);
}
}
My Drag targets:
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DragTarget(
onAccept: (LottieBuilder animation) {
setState(() {
widget.caughtAnimation = animation;
});
},
builder: (BuildContext context, List<dynamic> candidateData, List<dynamic> rejectedData) {
return Center(
child: Container(
height: 60,
width: 60,
decoration: BoxDecoration(
color: Colors.grey.shade400.withOpacity(0.5), borderRadius: BorderRadius.circular(20.0)),
child: widget.caughtAnimation,
),
);
},
),
Padding(
padding: const EdgeInsets.all(8.0),
child: DragTarget(
onAccept: (LottieBuilder animation) {
setState(() {
widget.caughtAnimation = animation;
});
},
builder: (BuildContext context, List<dynamic> candidateData, List<dynamic> rejectedData) {
return Center(
child: Container(
height: 60,
width: 60,
decoration: BoxDecoration(
color: Colors.grey.shade400.withOpacity(0.5),
borderRadius: BorderRadius.circular(20.0)),
child: widget.caughtAnimation,
),
);
},
),
),
DragTarget(
onAccept: (LottieBuilder animation) {
setState(() {
widget.caughtAnimation = animation;
});
},
builder: (BuildContext context, List<dynamic> candidateData, List<dynamic> rejectedData) {
return Center(
child: Container(
height: 60,
width: 60,
decoration: BoxDecoration(
color: Colors.grey.shade400.withOpacity(0.5), borderRadius: BorderRadius.circular(20.0)),
child: widget.caughtAnimation,
),
);
},
),
],
),
Again, thanks for any help!
This is happening because on each DragTarget you are building the same widget.caughtAnimation that you set on any onAccept callback.
Consider structuring your widget state model in a way that you can individually modify each DragTarget, this can be done with a List/array or a map.
List<LottieBuilder> caughtAnimations;
then
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DragTarget(
onAccept: (LottieBuilder animation) {
setState(() {
caughtAnimations[0] = animation;
});
},
builder: (BuildContext context, List<dynamic> candidateData, List<dynamic> rejectedData) {
return Center(
child: Container(
height: 60,
width: 60,
decoration: BoxDecoration(
color: Colors.grey.shade400.withOpacity(0.5), borderRadius: BorderRadius.circular(20.0)),
child: caughtAnimations[0],
),
);
},
),
Padding(
padding: const EdgeInsets.all(8.0),
child: DragTarget(
onAccept: (LottieBuilder animation) {
setState(() {
caughtAnimations[1] = animation;
});
},
builder: (BuildContext context, List<dynamic> candidateData, List<dynamic> rejectedData) {
return Center(
child: Container(
height: 60,
width: 60,
decoration: BoxDecoration(
color: Colors.grey.shade400.withOpacity(0.5),
borderRadius: BorderRadius.circular(20.0)),
child: caughtAnimations[1],
),
);
},
),
),
DragTarget(
onAccept: (LottieBuilder animation) {
setState(() {
caughtAnimations[2] = animation;
});
},
builder: (BuildContext context, List<dynamic> candidateData, List<dynamic> rejectedData) {
return Center(
child: Container(
height: 60,
width: 60,
decoration: BoxDecoration(
color: Colors.grey.shade400.withOpacity(0.5), borderRadius: BorderRadius.circular(20.0)),
child: caughtAnimations[2],
),
);
},
),
],
),

How to Integrate D-Pad Focus Navigation?

I'm currently trying to make a Netflix-style UI in Flutter on my Android TV. I've been struggling with integrating focus navigation for the past few days and figured I'd ask here as there doesn't really seem to be any in-depth tutorials.
Right now I'd like to be able to navigate my ListView Builder using d-pad controls and add a special state to the widget to signify that it's currently selected (enlarged or with a border).
Here's my current code:
class Home extends StatefulWidget {
Home({Key key}) : super(key: key);
#override
HomeState createState() => new HomeState();
}
class HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(left: 8.0, right: 8.0),
child: FutureBuilder(
// an asset :bundle is just the resources used by a given application
future: DefaultAssetBundle.of(context)
.loadString('assets/json/featured.json'),
builder: (context, snapshot) {
// Loading indicator
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text(snapshot.error); // or whatever
}
var mediaData = json.decode(snapshot.data.toString());
List<Session> mediaDataSession =
(mediaData as List<dynamic>).cast<Session>();
// Pass our array data into the Session class' fromJson method and allow it to be iterable
var decodedData =
mediaData.map((data) => Session.fromJson(data)).toList();
BoxDecoration myBoxDecoration() {
return BoxDecoration(
border: Border.all(),
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 30.0),
child: Align(
alignment: Alignment.bottomLeft,
child: Text('Featured',
style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'HelveticaNeue',
fontSize: 24.0)),
),
),
Expanded(
// Focus was here before
child: ListView.builder(
itemCount: mediaData.length,
scrollDirection: Axis.horizontal,
itemBuilder: (BuildContext context, int index) {
return Align(
alignment: Alignment.topLeft,
child: Container(
margin:
EdgeInsets.only(right: 8.0, top: 4.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment
.start, // Workaround for aligning text
children: [
Container(
// Find a way to render based on focus being true
decoration: myBoxDecoration(),
child: InkWell(
// onTap: () => {},
borderRadius: BorderRadius.circular(4.0),
focusColor: Colors.black,
child: SizedBox(
height: 150.0,
child: ClipRRect(
child: Image.network(
mediaData[index]['image'])),
),
),
),
Padding(
padding: const EdgeInsets.only(top: 6.0),
child: Text(mediaData[index]['name'],
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 17.0,
fontFamily: "HelveticaNeue",
fontWeight: FontWeight.normal)),
)
],
),
),
);
},
),
),
],
);
}),
);
}
}
For reference, I'd like to get behaviour like this video here: https://www.youtube.com/watch?v=l37VYXhRhPQ
Any help would be appreciated!
Here is the source code of the app in the video:
https://gitlab.com/ad-on-is/chillyflix/

Flutter : How to prevent rebuild of whole Reorderable Listview?

Currently I'm using flutter package 'Reorderables' to show a reorderable listview which contains several images.These images can be deleted from listview through a button , everything works fine. But the listview rebuild everytime when I delete an image. I'm using a class called 'ReorderableListviewManager' with ChangeNotifier to update images and Provider.of<ReorderableListviewManager>(context) to get latest images . The problem now is that using Provider.of<ReorderableListviewManager>(context) makes build() called everytime I delete an image , so the listview rebuid. I koow I
can use consumer to only rebuild part of widget tree, but it seems like that there's no place to put consumer in children of this Listview. Is there a way to rebuild only image but not whole ReorderableListview ? Thanks very much!
Below is my code:
class NotePicturesEditScreen extends StatefulWidget {
final List<Page> notePictures;
final NotePicturesEditBloc bloc;
NotePicturesEditScreen({#required this.notePictures, #required this.bloc});
static Widget create(BuildContext context, List<Page> notePictures) {
return Provider<NotePicturesEditBloc>(
create: (context) => NotePicturesEditBloc(),
child: Consumer<NotePicturesEditBloc>(
builder: (context, bloc, _) =>
ChangeNotifierProvider<ReorderableListviewManager>(
create: (context) => ReorderableListviewManager(),
child: NotePicturesEditScreen(
bloc: bloc,
notePictures: notePictures,
),
)),
dispose: (context, bloc) => bloc.dispose(),
);
}
#override
_NotePicturesEditScreenState createState() => _NotePicturesEditScreenState();
}
class _NotePicturesEditScreenState extends State<NotePicturesEditScreen> {
PreloadPageController _pageController;
ScrollController _reorderableScrollController;
List<Page> notePicturesCopy;
int longPressIndex;
List<double> smallImagesWidth;
double scrollOffset = 0;
_reorderableScrollListener() {
scrollOffset = _reorderableScrollController.offset;
}
#override
void initState() {
Provider.of<ReorderableListviewManager>(context, listen: false)
.notePictures = widget.notePictures;
notePicturesCopy = widget.notePictures;
_reorderableScrollController = ScrollController();
_pageController = PreloadPageController();
_reorderableScrollController.addListener(_reorderableScrollListener);
Provider.of<ReorderableListviewManager>(context, listen: false)
.getSmallImagesWidth(notePicturesCopy, context)
.then((imagesWidth) {
smallImagesWidth = imagesWidth;
});
super.initState();
}
#override
void dispose() {
_pageController.dispose();
_reorderableScrollController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
ReorderableListviewManager reorderableManager =
Provider.of<ReorderableListviewManager>(context, listen: false);
return SafeArea(
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
shape: Border(bottom: BorderSide(color: Colors.black12)),
iconTheme: IconThemeData(color: Colors.black87),
elevation: 0,
automaticallyImplyLeading: false,
titleSpacing: 0,
centerTitle: true,
title: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
child: IconButton(
padding: EdgeInsets.only(left: 20, right: 12),
onPressed: () => Navigator.of(context).pop(),
icon: Icon(Icons.close),
),
),
Text('編輯',
style: TextStyle(color: Colors.black87, fontSize: 18))
],
),
actions: <Widget>[
FlatButton(
onPressed: () {},
child: Text(
'下一步',
),
)
],
),
backgroundColor: Color(0xffeeeeee),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Spacer(),
StreamBuilder<List<Page>>(
initialData: widget.notePictures,
stream: widget.bloc.notePicturesStream,
builder: (context, snapshot) {
notePicturesCopy = snapshot.data;
return Container(
margin: EdgeInsets.symmetric(horizontal: 20),
height: MediaQuery.of(context).size.height * 0.65,
child: PreloadPageView.builder(
preloadPagesCount: snapshot.data.length,
controller: _pageController,
itemCount: snapshot.data.length,
onPageChanged: (index) {
reorderableManager.updateCurrentIndex(index);
reorderableManager.scrollToCenter(
smallImagesWidth,
index,
scrollOffset,
_reorderableScrollController,
context);
},
itemBuilder: (context, index) {
return Container(
child: Image.memory(
File.fromUri(
snapshot.data[index].polygon.isNotEmpty
? snapshot.data[index]
.documentPreviewImageFileUri
: snapshot.data[index]
.originalPreviewImageFileUri)
.readAsBytesSync(),
gaplessPlayback: true,
alignment: Alignment.center,
),
);
}),
);
},
),
Spacer(),
Container(
height: MediaQuery.of(context).size.height * 0.1,
margin: EdgeInsets.symmetric(horizontal: 20),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: ReorderableRow(
scrollController: _reorderableScrollController,
buildDraggableFeedback: (context, constraints, __) =>
Container(
width: constraints.maxWidth,
height: constraints.maxHeight,
child: Image.memory(File.fromUri(
notePicturesCopy[longPressIndex]
.polygon
.isNotEmpty
? notePicturesCopy[longPressIndex]
.documentPreviewImageFileUri
: notePicturesCopy[longPressIndex]
.originalPreviewImageFileUri)
.readAsBytesSync()),
),
onReorder: (oldIndex, newIndex) async {
List<Page> result = await widget.bloc.reorderPictures(
oldIndex,
newIndex,
reorderableManager.notePictures);
_pageController.jumpToPage(newIndex);
reorderableManager.updateNotePictures(result);
reorderableManager
.getSmallImagesWidth(result, context)
.then((imagesWidth) {
smallImagesWidth = imagesWidth;
});
},
footer: Container(
width: 32,
height: 32,
margin: EdgeInsets.only(left: 16),
child: SizedBox(
child: FloatingActionButton(
backgroundColor: Colors.white,
elevation: 1,
disabledElevation: 0,
highlightElevation: 1,
child: Icon(Icons.add, color: Colors.blueAccent),
onPressed: notePicturesCopy.length >= 20
? () {
Scaffold.of(context)
.showSnackBar(SnackBar(
content: Text('筆記上限為20頁 !'),
));
}
: () async {
List<Page> notePictures =
await widget.bloc.addPicture(
reorderableManager.notePictures);
List<double> imagesWidth =
await reorderableManager
.getSmallImagesWidth(
notePictures, context);
smallImagesWidth = imagesWidth;
reorderableManager.updateCurrentIndex(
notePictures.length - 1);
reorderableManager
.updateNotePictures(notePictures);
_pageController
.jumpToPage(notePictures.length - 1);
},
),
),
),
children: Provider.of<ReorderableListviewManager>(
context)
.notePictures
.asMap()
.map((index, page) {
return MapEntry(
index,
Consumer<ReorderableListviewManager>(
key: ValueKey('value$index'),
builder: (context, manager, _) =>
GestureDetector(
onTapDown: (_) {
longPressIndex = index;
},
onTap: () {
reorderableManager.scrollToCenter(
smallImagesWidth,
index,
scrollOffset,
_reorderableScrollController,
context);
_pageController.jumpToPage(index);
},
child: Container(
margin: EdgeInsets.only(
left: index == 0 ? 0 : 12),
decoration: BoxDecoration(
border: Border.all(
width: 1.5,
color: index ==
manager
.getCurrentIndex
? Colors.blueAccent
: Colors.transparent)),
child: index + 1 <=
manager.notePictures.length
? Image.memory(
File.fromUri(manager
.notePictures[
index]
.polygon
.isNotEmpty
? manager
.notePictures[
index]
.documentPreviewImageFileUri
: manager
.notePictures[
index]
.originalPreviewImageFileUri)
.readAsBytesSync(),
gaplessPlayback: true,
)
: null),
),
));
})
.values
.toList()),
)),
Spacer(),
Container(
decoration: BoxDecoration(
color: Colors.white,
border: Border(top: BorderSide(color: Colors.black12))),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
FlatButton(
onPressed: () async => await widget.bloc
.cropNotePicture(reorderableManager.notePictures,
_pageController.page.round())
.then((notePictures) {
reorderableManager.updateNotePictures(notePictures);
reorderableManager
.getSmallImagesWidth(notePictures, context)
.then((imagesWidth) {
smallImagesWidth = imagesWidth;
});
}),
child: Column(
children: <Widget>[
Icon(
Icons.crop,
color: Colors.blueAccent,
),
Container(
margin: EdgeInsets.only(top: 1),
child: Text(
'裁切',
style: TextStyle(color: Colors.blueAccent),
),
)
],
),
),
FlatButton(
onPressed: () {
int deleteIndex = _pageController.page.round();
widget.bloc
.deletePicture(
reorderableManager.notePictures, deleteIndex)
.then((notePictures) {
if (deleteIndex == notePictures.length) {
reorderableManager
.updateCurrentIndex(notePictures.length - 1);
}
reorderableManager.updateNotePictures(notePictures);
reorderableManager
.getSmallImagesWidth(notePictures, context)
.then((imagesWidth) {
smallImagesWidth = imagesWidth;
});
if (reorderableManager.notePictures.length == 0) {
Navigator.pop(context);
}
});
},
child: Column(
children: <Widget>[
Icon(
Icons.delete_outline,
color: Colors.blueAccent,
),
Container(
margin: EdgeInsets.only(top: 1),
child: Text(
'刪除',
style: TextStyle(color: Colors.blueAccent),
),
),
],
),
)
],
),
)
],
)),
);
}
}
You can't prevent a rebuild on your ReorderableListView widget because it will be rebuild every time there's an update on the Provider. What you can do here is to keep track the current index of all visible ListView items. When new data should be displayed coming from the Provider, you can retain the current indices of previous ListView items, and add the newly added items at the end of the list, or wherever you like.

Categories

Resources