Exception caught by widgets library Incorrect use of ParentDataWidget - flutter

When I am trying to display the data present in firebase realtime database. I am getting the error stating Exception caught by widgets library Incorrect use of ParentDataWidget.
class NotificationView extends StatefulWidget {
const NotificationView({Key key}) : super(key: key);
#override
State<NotificationView> createState() => _NotificationViewState();
}
class _NotificationViewState extends State<NotificationView> {
Map data;
List key;
#override
void initState() {
fetchData();
super.initState();
}
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Colors.white,
body: Container(
child: FutureBuilder(
future: fetchData(),
builder: (context, snapshot) {
if (data != null) {
return ListView.builder(
itemCount: data.values.length,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 100,
child: Card(
margin: EdgeInsets.fromLTRB(15, 5, 15, 15),
color: Colors.yellow[100],
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: Container(
margin: EdgeInsets.fromLTRB(15, 5, 15, 15),
child: Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(data[key[index]]['title']),
SizedBox(height: size.height * 0.01),
Text(data[key[index]]['message']),
],
),
),
),
),
);
});
} else {
return Center(child: CircularProgressIndicator());
}
})));
}
fetchData() async {
var userId = SharedUtils.getString('UserId');
final ref = FirebaseDatabase.instance.ref();
final snapshot =
await ref.child('users/62cfc3faf3e5df6648d32684/inApp').get();
debugPrint(snapshot.key + 'KEyyyyyyyyyyyyyyyyyyyyy');
data = snapshot.value;
key = data.keys.toList();
debugPrint(
'Listttttttttttttttofffffffffffkeyyyyyyyyyyyyyy&&&77' + key.toString());
}
}

You are using "Expanded" as the child of the container which is wrong. Be aware that, you can use the "Expanded" widget only as the child of columns, rows, and flex. That's why you are getting this "Incorrect use of ParentDataWidget".
More details for Expanded widget.

Related

Flutter Cubit fetching and displaying data

I'm trying to fetch data from Genshin API, code below is working, but only with delay (in GenshinCubit class), it looks weard, because I don't know how much time to set for delay. I think, there is a problem in code, cause it must not set the GenshinLoaded state before the loadedList is completed. Now, if I remove the delay, it just sets the GenshinLoaded when the list is still in work and not completed, await doesn't help. Because of that I get a white screen and need to hot reload for my list to display.
class Repository {
final String characters = 'https://api.genshin.dev/characters/';
Future<List<Character>> getCharactersList() async {
List<Character> charactersList = [];
List<String> links = [];
final response = await http.get(Uri.parse(characters));```
List<dynamic> json = jsonDecode(response.body);
json.forEach((element) {
links.add('$characters$element');
});
links.forEach((element) async {
final response2 = await http.get(Uri.parse(element));
dynamic json2 = jsonDecode(response2.body);
charactersList.add(Character.fromJson(json2));
});
return charactersList;
}
}
class GenshinCubit extends Cubit<GenshinState> {
final Repository repository;
GenshinCubit(this.repository) : super(GenshinInitial(),);
getCharacters() async {
try {
emit(GenshinLoading());
List<Character> list = await repository.getCharactersList();
await Future<void>.delayed(const Duration(milliseconds: 1000));
emit(GenshinLoaded(loadedList: list));
}catch (e) {
print(e);
emit(GenshinError());
}
}
}
class HomeScreen extends StatelessWidget {
final userRepository = Repository();
HomeScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return BlocProvider<GenshinCubit>(
create: (context) => GenshinCubit(userRepository)..getCharacters(),
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(body: Container(child: const CharactersScreen())),
),
);
}
}
class CharactersScreen extends StatefulWidget {
const CharactersScreen({
Key? key,
}) : super(key: key);
#override
State<CharactersScreen> createState() => _CharactersScreenState();
}
class _CharactersScreenState extends State<CharactersScreen> {
#override
Widget build(BuildContext context) {
return Column(
children: [
BlocBuilder<GenshinCubit, GenshinState>(
builder: (context, state) {
if (state is GenshinLoading) {
return Center(
child: CircularProgressIndicator(),
);
}
if (state is GenshinLoaded) {
return SafeArea(
top: false,
child: Column(
children: [
Container(
color: Colors.black,
height: MediaQuery.of(context).size.height,
child: ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: state.loadedList.length,
itemBuilder: ((context, index) {
return Padding(
padding: const EdgeInsets.symmetric(
vertical: 50.0, horizontal: 50),
child: GestureDetector(
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CharacterDetailsPage(
character: state.loadedList[index],
),
),
),
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: Colors.blueAccent.withOpacity(0.3),
borderRadius: const BorderRadius.all(
Radius.circular(
30,
),
)),
child: Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.only(
right: 30.0, bottom: 30),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
state.loadedList[index].name
.toString(),
style: TextStyle(
color: Colors.black,
fontSize: 50),
),
RatingBarIndicator(
itemPadding: EdgeInsets.zero,
rating: double.parse(
state.loadedList[index].rarity
.toString(),
),
itemCount: int.parse(
state.loadedList[index].rarity
.toString(),
),
itemBuilder: (context, index) =>
Icon(
Icons.star_rate_rounded,
color: Colors.amber,
))
],
),
),
),
),
),
);
})),
),
],
),
);
}
if (state is GenshinInitial) {
return Text('Start');
}
if (state is GenshinError) {
return Text('Error');
}
return Text('Meow');
}),
],
);
}
}
I found a solution!
I've got that problem because of forEach. How to wait for forEach to complete with asynchronous callbacks? - there is a solution.

Why i am not able to use setState Under GestureDetector

Why I am not able to use setState Under GestureDetector Using onTap:
After I use setState I got an error like: The function 'setState' isn't defined.
Try importing the library that defines 'setState', And VS Code editor show me
Error like: correcting the name to the name of an existing function, or defining a function named 'setState'.dart(undefined_function).
I try to fix different ways please tell me where is my problem
Thank you
Some Flutter Import Link ::::::::::
class ParsingMap extends StatefulWidget {
const ParsingMap({Key? key}) : super(key: key);
#override
_ParsingMapState createState() => _ParsingMapState();
}
class _ParsingMapState extends State<ParsingMap> {
Future<ApiList>? data;
#override
void initState() {
super.initState();
Network network = Network("https://fakestoreapi.com/products");
data = network.loadPosts();
// print(data);
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
elevation: 0,
leading: Icon(Icons.arrow_left, color: Colors.black),
actions: [
Icon(Icons.search, color: Colors.black),
SizedBox(width: 10),
Icon(Icons.home_filled, color: Colors.black),
SizedBox(width: 8)
],
),
body: Center(
child: Container(
child: FutureBuilder(
future: data,
builder: (context, AsyncSnapshot<ApiList> snapshot) {
List<Api> allPosts;
if (snapshot.hasData) {
allPosts = snapshot.data!.apis!;
return createListView(allPosts, context);
}
return CircularProgressIndicator();
},
),
),
),
);
}
}
class Network {
final String url;
Network(this.url);
Future<ApiList> loadPosts() async {
final response = await get(Uri.parse(url));
if (response.statusCode == 200) {
// print(response.body);
return ApiList.fromJson(json.decode(response.body));
} else {
throw Exception("Faild To get posts");
}
}
}
Widget createListView(List<Api> data, BuildContext context) {
return ListView(
children: [
Container(
height: 300,
margin: EdgeInsets.symmetric(vertical: 16),
child: ListView.builder(
itemCount: data.length,
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
padding: EdgeInsets.symmetric(horizontal: 16),
itemBuilder: (context, index) {
int selectedIndex = 0;
return GestureDetector(
onTap: () {
setState(() {
selectedIndex = index;
});
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${data[index].category}",
style: TextStyle(
fontWeight: FontWeight.bold,
color: selectedIndex == index
? Colors.black
: Colors.black38),
),
Container(
margin: EdgeInsets.only(
top: 5,
),
height: 2,
width: 30,
color: selectedIndex == index
? Colors.black
: Colors.transparent,
)
],
),
),
);
},
),
),
],
);
}
Put top-level createListView function in _ParsingMapState class.
class _ParsingMapState extends State<ParsingMap> {
// ...
Widget createListView(...) {}
}

filtering Streambuilder/ listviewBuilder flutter

i am new to flutter and been trying to create a function that refresh the ListView.builder based on users choice.i am saving cities names as Strings inside my firestore documents in user collection.
i have multiple buttons that presents different cities and based on choice i need the ListView builder to rebuild. i have been struggling for a while trying to find the solution to this.
anyone here can help?
this is how i retrieve data from firestore
StreamBuilder(
stream: Firestore.instance.collection('users').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Text('loading...');
return Container(
width: 890.0,
height: 320.0,
margin: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 00.0),
child: new ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) {
User user = User.fromDoc(snapshot.data
.documents[index]);
return Padding(
padding: const EdgeInsets.only(top: 0),
child: Container(
height: 300,
width: 300,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(0),
),
child: _buildCard(user)),
);
}),
);
},
),
I just wrote this code to show the implementation for static no of cities, clicking the buttons changes the index which then changes the texts(you will change them to stream builders with custom city streams), you can also scale it to dynamic list by manipulating the city list.
class MyHomePage extends StatefulWidget {
MyHomePage({Key key,}) : super(key: key);
​
​
#override
_MyHomePageState createState() => _MyHomePageState();
}
​
class _MyHomePageState extends State<MyHomePage> {
int stackIndex = 0;
​
final List<String> cities = ['Berlin', 'Denver', 'Nairobi', 'Tokyo', 'Rio'];
​
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Sample'),
),
body: Center(
child: Column(
mainAxisAlignment : MainAxisAlignment.spaceEvenly,
children : [
Row(
mainAxisAlignment : MainAxisAlignment.spaceEvenly,
mainAxisSize : MainAxisSize.max,
children : cities.map((city){
return RaisedButton(
child : Text(city),
onPressed : (){
setState((){
this.stackIndex = cities.indexOf(city);
});
}
);
}).toList()
),
IndexedStack(
index : stackIndex,
children: cities.map((city){
return yourStreamBuilder(city);
}).toList()
),
])
),
);
}
Widget yourStreamBuilder(String city){
//you can use your custom stream here
//Stream stream = Firestore.instance.collection('users').where('myCity', isEqualTo: city).snapshots();
​
​
return Text(city);//replace this with your streamBuilder
}
}
​
int stackIndex = 0;
final List<String> cities =[
'Stockholm',
'Malmö',
'Uppsala',
'Västerås',
'Örebro',
'Linköping',
'Helsingborg',
'Jönköping',
'Norrköping',
'Lund',
'Umeå',
'Gävle',
'Södertälje',
'Borås',
'Huddinge',
'Eskilstuna',
'Nacka',
'Halmstad',
'Sundsvall',
'Södertälje',
'Växjö',
'Karlstad',
'Haninge',
'Kristianstad',
'Kungsbacka',
'Solna',
'Järfälla',
'Sollentuna',
'Skellefteå',
'Kalmar',
'Varberg',
'Östersund',
'Trollhättan',
'Uddevalla',
'Nyköping',
'Skövde',
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment : MainAxisAlignment.spaceEvenly,
children: <Widget>[
Row(
mainAxisAlignment : MainAxisAlignment.spaceEvenly,
mainAxisSize : MainAxisSize.max,
children: cities.map((city) {
return OutlineButton(
child: Text(city),
onPressed: (){
setState(() {
this.stackIndex = cities.indexOf(city);
});
},
);
}).toList()
),
IndexedStack(
index: stackIndex,
children: cities.map((city){
return myStreamBuilder(city);
})
)
],
),
),
);
}
Widget myStreamBuilder(String city){
Stream stream = Firestore.instance.collection('users').where('myCity', isEqualTo: city).snapshots();
return Text(city);
}
}

Flutter - Returning to previous page from AppBar is not refreshing the page, with Navigator.pop(context)

I was trying to get the list page refreshed if a method was run on another page. I do pass the context using the push navigation.
I tried to follow these 3 answers Answer 1 Answer 2 and Answer 3 and I am not able to manage the states here.
This is the first list page which needs to be refreshed. It calls a class
class _PageLocalState extends State<PageLocal> {
#override
Widget build(BuildContext context) {
return Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: SafeArea(
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: widget.allLocal.length,
//padding: const EdgeInsets.only(top: 10.0),
itemBuilder: (context, index) {
return LocalCard(widget.allLocal[index]);
},
)),
)
],
),
);
}
}
The next class:
class LocalCardState extends State<LocalCard> {
FavData localdet;
LocalCardState(this.localdet);
ListTile makeListTile() => ListTile(
contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
title: Text(
localdet.name,
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(localdet.loc),
trailing: Icon(Icons.keyboard_arrow_right, size: 30.0),
onTap: () => navigateToDetail(localdet),
);
Widget get localCard {
return new Card(
elevation: 4.0,
margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
child: Container(
child: makeListTile(),
));
}
#override
Widget build(BuildContext context) {
return new Container(
child: localCard,
);
}
navigateToDetail(FavData localdet) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavouriteDetailPage(
mndet: localdet,
)));
setState(() {});
}
}
Now this is routing to the final detail page:
class _FavouriteDetailPageState extends State<FavouriteDetailPage> {
bool isFav = false;
FavData mndet;
_FavouriteDetailPageState(this.mndet);
// reference to our single class that manages the database
final dbHelper = DatabaseHelper.instance;
#override
Widget build(BuildContext context) {
Widget heading = new Container(...);
Widget middleSection = new Expanded(...);
Widget bottomBanner = new Container(...);
Widget body = new Column(...);
final makeBottom = Container(
height: 55.0,
child: BottomAppBar(
color: Color.fromRGBO(36, 36, 36, 1.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new FavIconWidget(mndet),
],
),
),
);
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('The Details'),
backgroundColor: Color.fromRGBO(36, 36, 36, 1.0),
),
body: Container(
child: Card(
elevation: 5.0,
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.white70, width: 1),
borderRadius: BorderRadius.circular(10),
),
margin: EdgeInsets.all(20.0),
child: Padding(
padding: new EdgeInsets.symmetric(vertical: 16.0, horizontal: 16.0),
child: body,
),
),
),
bottomNavigationBar: makeBottom,
);
}
void share(BuildContext context, FavData mndet) {
final RenderBox box = context.findRenderObject();
final String shareText = "${mndet.name} - ${mndet.desc}";
Share.share(shareText,
subject: mndet.loc,
sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
}
}
class FavIconWidget extends StatefulWidget {
final FavData mnforIcon;
FavIconWidget(this.mnforIcon);
#override
_FavIconWidgetState createState() => _FavIconWidgetState();
}
class _FavIconWidgetState extends State<FavIconWidget> {
final dbHelper = DatabaseHelper.instance;
Future<bool> get isFav async {
final rowsPresent = await dbHelper.queryForFav(widget.mnforIcon.id);
if (rowsPresent > 0) {
print('Card Loaded - Its Favourite already');
return false;
} else {
print('Card Loaded - It is not favourite yet');
return true;
}
}
void _insert() async {...}
void _delete() async {...}
#override
Widget build(BuildContext context) {
return FutureBuilder<bool>(
future: isFav,
initialData:
false, // you can define an initial value while the db returns the real value
builder: (context, snapshot) {
if (snapshot.hasError)
return const Icon(Icons.error,
color: Colors.red); //just in case the db return an error
if (snapshot.hasData)
return IconButton(
icon: snapshot.data
? const Icon(Icons.favorite_border, color: Colors.white)
: Icon(Icons.favorite, color: Colors.red),
onPressed: () => setState(() {
if (!snapshot.data) {
print('Its favourite so deleting it.');
_delete();
} else {
print('Wasnt fav in the first place so inserting.');
_insert();
}
}));
return CircularProgressIndicator(); //if there is no initial value and the future is not yet complete
});
}
}
I am sure this is just some silly coding I have done but just not able to find out. Where.
I tried adding Navigator.pop(context); in different sections of the detail page and it fails.
Currently, I have to navigate back to the Favourites list page and then HomePage and then back to Favourites ListPage to refresh the list.
try this.. Anywhere you are using Navigator.pop or Navigator.push .. Instead of this use this:
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (BuildContext context) => Password())
);
//instead of Password use the name of the page(the second page you want to go to)

problems with video player flutter

I'm new in Flutter and try to load video from api, but video player is not working correctly. I have PageView in my Widget _buildFilmsMainPages() and each Page will get own video from api.
i'm getting error while data is loading: The following NoSuchMethodError was thrown building FutureBuilder>(dirty, state: _FutureBuilderState>#033d3):
The method '[]' was called on null.
Receiver: null
Tried calling:
After loading this error is gone.
when i tap on play (Floating Action Button) i see only first frame of video but sound is working.
when i tap on stop (Floating Action Button) first frame of video is gone but sound is still working.
class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_ HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
VideoPlayerController _controller;
Future<void> _initializeVideoPlayerFuture;
bool isVideo = false;
int filmIndex = 0;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold (
body: SingleChildScrollView(
child: _buildFilmsMainPages(),
)
);
}
Widget _buildFilmsMainPages() =>
FutureBuilder(
future:getMoviesListByDay(date))),
builder: (BuildContext context, AsyncSnapshot snapshot) {
without this code i get error, but player isn't working
correctly anyway and i'm getting error while data is loading
_controller= VideoPlayerController.network
(snapshot.data[filmIndex].media!=null?
snapshot.data[filmIndex].media.elementAt(1)
:"https://flutter.github.io/assets-for-api-
docs/assets/videos/butterfly.mp4");
_initializeVideoPlayerFuture =_controller.initialize();
_controller.setLooping(true);
if (snapshot.data != null) {
return
Column(
children:<Widget> [
SizedBox(
height: 460.0,
child: PageView.builder(
pageSnapping: true,
itemCount: snapshot.data.length,
onPageChanged: (int index) {
setState(() {
filmIndex = index;
i thought i should write this code here
_controller = VideoPlayerController.network
(snapshot.data[filmIndex].media!=null?
snapshot.data[filmIndex].media.elementAt(1)
:"https://flutter.github.io/assets-for-api-
docs/assets/videos/butterfly.mp4");
_initializeVideoPlayerFuture =
_controller.initialize();
_controller.setLooping(true);
});
},
itemBuilder: (context, index) {
return Column(
children: <Widget>[
Container(margin: const
EdgeInsets.symmetric(horizontal: 16.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Container(
height: 250.0,
child: Stack(children: <Widget>[
Container(
child: GestureDetector(
child: isVideo ?
FutureBuilder(
future:_initializeVideoPlayerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState ==
ConnectionState.done) {
return AspectRatio(
aspectRatio: 16.0 / 12.0,
child:VideoPlayer(_controller),
);
} else {
return Center(
child:
CircularProgressIndicator());
}
},
) :
FadeInImage.assetNetwork(
placeholder:
"assets/placeholder.jpg",
image:
snapshot.data[index].media!=null
? snapshot.data[index].media.elementAt(0): "",
fit: BoxFit.fill,
fadeInDuration:Duration(milliseconds: 50),
),
onTap: () =>
)
),
)
)
),
Row(children: <Widget>[
Container(
margin: const EdgeInsets.only(left: 16.0,
right: 16.0, top: 190.0),
height: 40.0,
width: 40.0,
child: FittedBox(
child: FloatingActionButton(
backgroundColor: Colors.white,
foregroundColor: Colors.black,
onPressed: () {
setState(() {
isVideo = !isVideo;
if (_controller.value.isPlaying) {
_controller.pause();
} else {
_controller.play();
}
});
},
child: Icon(_controller.value.isPlaying
? Icons.pause : LineIcons.play,
size: 30.0,)
),
)
);