The operator '[]' isn't defined for the type 'Type'. Try defining the operator '[]' - flutter

I have a home screen where at the top I declared a listview, with scrolldirection taking information from a list.dart file. This horizontal scrolling screen brings me 5 images and a text in each of them. I would like to insert an onpress directing to other screens according to the information passed in this list. Example: Chat, direct to chat.screen.
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
Container(
width: double.infinity,
height: MediaQuery.of(context).size.height * 4 / 7,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0xff40dedf), Color(0xff0fb2ea)],
),
),
),
Positioned(
top: 100,
left: 20,
child: Container(
height: 100,
width: MediaQuery.of(context).size.width,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: categoryData.length,
itemBuilder: (context, index) {
bool isSelected = true;
if (index == 0) {
isSelected = true;
}
Navigator.push<dynamic>(
context,
MaterialPageRoute<dynamic>(
builder: (BuildContext
context) =>
HomeList[index].navigateScreen,
),
);
return Row(
children: <Widget>[
Column(
children: <Widget>[
Container(
width: 65,
height: 65,
decoration: BoxDecoration(
color: isSelected
? Colors.transparent
: Colors.transparent,
borderRadius:
BorderRadius.circular(16),
border: Border.all(
color: Colors.white,
width: 1,
),
boxShadow: isSelected
? [
BoxShadow(
color: Color(0x14000000),
blurRadius: 10)
]
: null),
child: Center(
child: Image.asset(categoryData[index].imageUrl),
),
),
SizedBox(
height: 10,
),
Text(
categoryData[index].name,
style: TextStyle(color: Colors.white, fontSize: 15),
),
],
),
SizedBox(
width: 20,
)
],
);
},
),
),
),
Homelist
import 'package:flutter/material.dart';
import 'package:projeto/pages/chat.screen.dart';
class HomeList {
HomeList({
this.navigateScreen,
this.imagePath = '',
});
Widget navigateScreen;
String imagePath;
static List<HomeList> homeList = [
HomeList(
imagePath: 'assets/page1/usuario.png',
navigateScreen: ChatScreen(),
),
HomeList(
imagePath: 'assets/page1/entregas.png',
navigateScreen: ChatScreen(),
),
HomeList(
imagePath: 'assets/page1/msg.png',
navigateScreen: ChatScreen(),
),
HomeList(
imagePath: 'assets/page1/configurações.png',
navigateScreen: ChatScreen(),
),
HomeList(
imagePath: 'assets/page1/sair.png',
navigateScreen: ChatScreen(),
),
];
}

from what i understand, you want to transform the data in your HomeList file to a listview where clicking on one of its items takes you to its related page, you could use a ListView.builder with an itemBuilder and itemCount, the code below shows how you can achieve a listView where items are images with text in them and an onTap function:
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return GestureDetector(
child: Stack(
children: <Widget>[
Image.asset(
homeList[index].imagePath,
),
Positioned(child: Text())
],
),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => homeList[index].navigateScreen),
),
);
},
itemCount: homeList.length,
),
);
}
}

Related

How do i get the image path of selected images in a gridview in flutter?

I have a stateful widget called AddPhotosView that contains all the logic i am trying to achieve, i am using this package photo_manager to display images in the user's devices in a GridView.builder and i am trying to use image_cropper to be able to crop the image the user selects in the from the grid view.
This is the full code of my stateful widget :
class AddPhotosView extends StatefulWidget {
#override
State<AddPhotosView> createState() => _AddPhotosView();
}
class _AddPhotosView extends State<AddPhotosView> {
List<Widget> _mediaList = [];
int currentPage = 0;
int lastPage;
#override
void initState() {
super.initState();
_fetchNewMedia();
}
_handleScrollEvent(ScrollNotification scroll) {
if (scroll.metrics.pixels / scroll.metrics.maxScrollExtent > 0.33) {
if (currentPage != lastPage) {
_fetchNewMedia();
}
}
}
_fetchNewMedia() async {
var result = await PhotoManager.requestPermissionExtend();
if (result != null) {
// success
//load the album list
List<AssetPathEntity> albums =
await PhotoManager.getAssetPathList(onlyAll: true);
print(albums);
List<AssetEntity> media =
await albums[0].getAssetListPaged(page: currentPage, size: 60);
print(media);
List<Widget> temp = [];
for (var asset in media) {
temp.add(
FutureBuilder(
future: asset.thumbnailDataWithSize(
ThumbnailSize(200, 200),
),
builder: (BuildContext context, snapshot) {
if (snapshot.connectionState == ConnectionState.done)
return GestureDetector(
onTap: () async {
File file = await asset.file;
print(file.toString());
},
child: Stack(
children: <Widget>[
Positioned.fill(
child: Image.memory(
snapshot.data,
fit: BoxFit.cover,
),
),
if (asset.type == AssetType.video)
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: EdgeInsets.only(right: 5, bottom: 5),
child: Icon(
Icons.videocam,
color: Colors.white,
),
),
),
],
),
);
return Container();
},
),
);
}
setState(() {
_mediaList.addAll(temp);
currentPage++;
});
} else {
// fail
PhotoManager.openSetting();
}
}
#override
Widget build(BuildContext context) {
// final controller = Get.put(EServicesController());
return Scaffold(
appBar: AppBar(
toolbarHeight: 50,
backgroundColor: Colors.white,
title: Column(
children: [
Text(
"Add Photos".tr,
style: GoogleFonts.poppins(
color: Color(0xff000000),
fontSize: 16,
fontWeight: FontWeight.w600),
),
],
),
centerTitle: false,
elevation: 0.5,
automaticallyImplyLeading: false,
leadingWidth: 15,
leading: new IconButton(
icon: new Icon(Icons.arrow_back_ios, color: Color(0xff3498DB)),
onPressed: () => {Get.back()},
),
),
body: Column(
children: [
Container(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.only(
left: 45.0, right: 45, top: 22, bottom: 35),
child: Container(
height: 280,
width: 280,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
),
child: Stack(
fit: StackFit.expand,
children: [
Image.asset(
'assets/icon/image-test.png',
fit: BoxFit.cover,
),
ColorFiltered(
colorFilter: ColorFilter.mode(
Colors.white.withOpacity(0.3),
BlendMode.srcOut), // This one will create the magic
child: Stack(
fit: StackFit.expand,
children: [
Container(
decoration: BoxDecoration(
color: Colors.black,
backgroundBlendMode: BlendMode
.dstOut), // This one will handle background + difference out
),
Align(
alignment: Alignment.topCenter,
child: Container(
margin: const EdgeInsets.only(top: 80),
height: 200,
width: 200,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(100),
),
),
),
],
),
),
],
),
),
),
),
Expanded(
child: NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification scroll) {
_handleScrollEvent(scroll);
return;
},
child: Padding(
padding: const EdgeInsets.all(22.0),
child: GridView.builder(
itemCount: _mediaList.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3),
itemBuilder: (BuildContext context, int index) {
return _mediaList[index];
}),
),
),
),
],
),
//bottomNavigationBar: SendUpdateButton(),
);
}
}
My photo_manager package is working and displaying my images correctly, but i want to more with it.
Want i am trying to achieve :
Get the image path of an image selected by the user with the photo_manager package.
I also want to be able select multiple images at once or a single image when tapped from the grid view.
Then render the image selected by the user in the Container carrying the image.asset() widget.
Crop the image using the flutter package image_cropper.
Getting the file path of an image selected by the user is very important as i believe it can help me achieve many other logic.
I have tried getting the image path by wrapping the container carrying the image.asset with
GestureDetector(
onTap: () async {
File file = await asset.file;
print(file.toString());
},
But it don't to work :(
Please i would be entirely grateful if someone help me out with what i am trying to achieve as i have been struggling to achieve this for sometime now in my project.
NB: I am using the package: photo_manager because it helps me to customise the UI of where the user's gallery can be displayed, other packages has an out-of-the-box UI which i don't want. So i will be open to using another package for only cropping the image if possible.

How can i achieve 'add photo' logic in flutter?

Hey guys i am trying to achieve this image logic in flutter as i am new to flutter.
First off...
Images from the user gallery are being rendered in the 'Recent' Grid view UI (Should be in the UI provided and not come out as an overlay page as different pub.dev image picker packages does)
Images are selectable, both multiple selection and single selection.
Any image selected should be rendered inn the big container that has a round hole and an overlay, which can be cropped and zoomed.
any image selected would then be rendered in the sized boxes with the 'x'. when the 'x' is tapped, the image should be unselected.
This is what i am trying to achieve in a picture, the UI is not a problem but the logic has been giving me sleepless nights.
I tried using photo_manager
and it helped me to render the user's gallery image in the 'recent' but i am stuck at the rest logic.
Please help me :(
This is what i tried.
class AddPhotosView extends StatefulWidget {
#override
State<AddPhotosView> createState() => _AddPhotosView();
}
class _AddPhotosView extends State<AddPhotosView> {
List<Widget> _mediaList = [];
int currentPage = 0;
int lastPage;
#override
void initState() {
super.initState();
_fetchNewMedia();
}
_handleScrollEvent(ScrollNotification scroll) {
if (scroll.metrics.pixels / scroll.metrics.maxScrollExtent > 0.33) {
if (currentPage != lastPage) {
_fetchNewMedia();
}
}
}
_fetchNewMedia() async {
var result = await PhotoManager.requestPermissionExtend();
if (result != null) {
// success
//load the album list
List<AssetPathEntity> albums =
await PhotoManager.getAssetPathList(onlyAll: true);
print(albums);
List<AssetEntity> media =
await albums[0].getAssetListPaged(page: currentPage, size: 60);
print(media);
List<Widget> temp = [];
for (var asset in media) {
temp.add(
FutureBuilder(
future: asset.thumbnailDataWithSize(
ThumbnailSize(200, 200),
),
builder: (BuildContext context, snapshot) {
if (snapshot.connectionState == ConnectionState.done)
return GestureDetector(
onTap: () async {
File file = await asset.file;
print(file.toString());
},
child: Stack(
children: <Widget>[
Positioned.fill(
child: Image.memory(
snapshot.data,
fit: BoxFit.cover,
),
),
if (asset.type == AssetType.video)
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: EdgeInsets.only(right: 5, bottom: 5),
child: Icon(
Icons.videocam,
color: Colors.white,
),
),
),
],
),
);
return Container();
},
),
);
}
setState(() {
_mediaList.addAll(temp);
currentPage++;
});
} else {
// fail
PhotoManager.openSetting();
}
}
#override
Widget build(BuildContext context) {
// final controller = Get.put(EServicesController());
return Scaffold(
appBar: AppBar(
toolbarHeight: 50,
backgroundColor: Colors.white,
title: Column(
children: [
Text(
"Add Photos".tr,
style: GoogleFonts.poppins(
color: Color(0xff000000),
fontSize: 16,
fontWeight: FontWeight.w600),
),
],
),
centerTitle: false,
elevation: 0.5,
automaticallyImplyLeading: false,
leadingWidth: 15,
leading: new IconButton(
icon: new Icon(Icons.arrow_back_ios, color: Color(0xff3498DB)),
onPressed: () => {Get.back()},
),
),
body: Column(
children: [
Container(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.only(
left: 45.0, right: 45, top: 22, bottom: 35),
child: Container(
height: 280,
width: 280,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
),
child: Stack(
fit: StackFit.expand,
children: [
Image.asset(
'assets/icon/image-test.png',
fit: BoxFit.cover,
),
ColorFiltered(
colorFilter: ColorFilter.mode(
Colors.white.withOpacity(0.3),
BlendMode.srcOut), // This one will create the magic
child: Stack(
fit: StackFit.expand,
children: [
Container(
decoration: BoxDecoration(
color: Colors.black,
backgroundBlendMode: BlendMode
.dstOut), // This one will handle background + difference out
),
Align(
alignment: Alignment.topCenter,
child: Container(
margin: const EdgeInsets.only(top: 80),
height: 200,
width: 200,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(100),
),
),
),
],
),
),
],
),
),
),
),
Expanded(
child: NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification scroll) {
_handleScrollEvent(scroll);
return;
},
child: Padding(
padding: const EdgeInsets.all(22.0),
child: GridView.builder(
itemCount: _mediaList.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3),
itemBuilder: (BuildContext context, int index) {
return _mediaList[index];
}),
),
),
),
],
),
//bottomNavigationBar: SendUpdateButton(),
);
}
}

how to scroll search widget along with the list view result flutter

How to scroll the search widget along with the list view result flutter whenever I use singlechildscrollview it gives an error.Help me to solve the issue.
How to scroll the search widget along with the list view result flutter whenever I use singlechildscrollview it gives an error.Help me to solve the issue
import 'package:coronavirus_app/Services/states_services.dart';
import 'package:coronavirus_app/resources/sizeconfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shimmer/shimmer.dart';
import '../Modal/world_countries_modal.dart';
import '../resources/colormanager.dart';
import '../resources/routesmanager.dart';
class CountriesListScreen extends ConsumerStatefulWidget {
const CountriesListScreen({Key? key}) : super(key: key);
#override
ConsumerState<CountriesListScreen> createState() =>
_CountriesListScreenState();
}
class _CountriesListScreenState extends ConsumerState<CountriesListScreen> {
final TextEditingController searchcontroller = TextEditingController();
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
StatesServices services = StatesServices();
final countrydata = ref.watch(countrydataProvider);
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
),
body: countrydata.when(
error: (err, stack) => Text('Error: ${err.toString()}'),
loading: () => Shimmer.fromColors(
baseColor: ColorManager.grey,
highlightColor: ColorManager.lightGrey,
child: ListView.builder(
itemCount: 5,
itemBuilder: ((context, index) {
return Column(
children: [
ListTile(
title: Container(
height: getProportionateScreenHeight(20),
width: getProportionateScreenWidth(89),
color: ColorManager.white,
),
leading: SizedBox(
height: getProportionateScreenHeight(100),
width: getProportionateScreenWidth(50),
child: Container(
color: ColorManager.white,
)),
subtitle: Container(
height: getProportionateScreenHeight(20),
width: getProportionateScreenWidth(89),
color: ColorManager.white,
),
)
],
);
})),
),
data: ((data) {
List<WorldCountriesModal> countrieslist =
data.map((e) => e).toList();
return Column(children: [
SizedBox(
height: getProportionateScreenHeight(50),
width: double.infinity,
child: TextFormField(
controller: searchcontroller,
onChanged: (value) {
setState(() {});
},
decoration: InputDecoration(
contentPadding:
const EdgeInsets.symmetric(vertical: 10),
hintText: 'Search with country name',
prefixIcon: const Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50))),
),
),
Expanded(
child: ListView.builder(
itemCount: countrieslist.length,
itemBuilder: ((context, index) {
var data = countrieslist[index];
var countrydata = countrieslist[index].country;
if (searchcontroller.text.isEmpty) {
return Column(
children: [
InkWell(
onTap: (() {
FocusScope.of(context).unfocus();
Navigator.pushNamed(context, Routes.detail,
arguments: data);
}),
child: ListTile(
title: Text(data.country.toString()),
leading: SizedBox(
height: getProportionateScreenHeight(100),
width: getProportionateScreenWidth(50),
child: Image(
image: Image.network(data
.countryInfo!.flag
.toString())
.image),
),
subtitle: Text(data.cases.toString()),
),
)
],
);
} else if (countrydata!
.toLowerCase()
.contains(searchcontroller.text.toLowerCase())) {
return Column(
children: [
InkWell(
onTap: (() {
FocusScope.of(context).unfocus();
Navigator.pushNamed(context, Routes.detail,
arguments: data);
}),
child: ListTile(
title: Text(data.country.toString()),
leading: SizedBox(
height: getProportionateScreenHeight(100),
width: getProportionateScreenWidth(50),
child: Image(
image: Image.network(data
.countryInfo!.flag
.toString())
.image),
),
subtitle: Text(data.cases.toString()),
),
)
],
);
} else {
return Container(
height: 0,
);
}
})),
),
]);
})
}
}
ListView.builder(
shrinkWrap: true,
primary: false
Hey If you want to use singlechildscrollview then you need to assign
ListView.builder(
shrinkWrap: true
to your ListView.builder.
Because you can't assign the 2 scroll views to your screen at a time.
Put your widgets in SingleChildScrollView widget as the following example:
return Scaffold(
appBar: AppBar( ..........) ,
body: Container(
margin: const EdgeInsets.only(top: 15, right: 10),
alignment: Alignment.topRight,
width: double.infinity,
height: double.infinity,
==> child:SingleChildScrollView(
scrollDirection: Axis.vertical,
child: .......

Flutter State won't update

I'm trying to create a listview of cards whose images get displayed in the listview only if the card is selected. The selection widget is the PopupSubscription() where I'm choosing which cards (SubscriptionCard) to display by setting the bool of that particular image to be true. But when the selections are applied, the selected images don't appear immediately even after doing setState().
However, they do appear when I switch tabs and return the screen again. What should I do in order to change the state of an object that's not in my current state class? I tried using Provider but it left me confused as to what I'm supposed to do.
This is the SubscriptionCard where the bool is set on tapping it:
return InkWell(
radius: 1.0,
borderRadius: BorderRadius.circular(8.0),
highlightColor: buttonBackground,
onTap: () {
setState(() {
widget.currentSubscription.selected = !widget.currentSubscription.selected;
});
},
child: Card(
elevation: 1.0,
borderOnForeground: true,
shape: widget.currentSubscription.selected ? RoundedRectangleBorder(
borderRadius: BorderRadius.circular(3.0),
side: BorderSide(color: buttonBackground, width: 2.0),
) : ContinuousRectangleBorder(),
color: bgDarkColor,
child: SizedBox(
width: SizeConfig.blockSizeHorizontal * 30,
child: Stack(
alignment: Alignment.topRight,
children: [
Row(
mainAxisSize: MainAxisSize.max,
children: [
Image.asset(this.widget.currentSubscription.logo, height: 35.0,),
Text(
' ${this.widget.currentSubscription.name}',
style: TextStyle(fontFamily: 'Muli', fontSize: 16.0)
),
],
),
widget.currentSubscription.selected ? Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: buttonBackground,
),
child: Padding(
padding: const EdgeInsets.all(2.0),
child: Icon(
Icons.check,
size: 10.0,
color: Colors.white,
),
),
) : Container()
],
),
),
),
);
This is the ListView where the selected cards' images are rendered:
Container(
height: 50,
width: 350,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
IconButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return PopupSubscription();
}
);
},
icon: Icon(Icons.add_box_rounded, size: 30.0,),
),
StatefulBuilder(
builder: (context, setState) {
return ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: subscriptionsList.length,
itemBuilder: (context, index) {
return Container(
margin: EdgeInsets.symmetric(horizontal: 5.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(25.0),
child: Image.asset(
subscriptionsList[index].selected ? subscriptionsList[index].logo
: "assets/elements/streaming-services/netflix.jpeg",
),
),
);
},
);
}
),
],
)
),
Based on your current code, I'm guessing you've added the currentSubscription variable as final in the StatefulWidget above the actual State, like:
class MyClass extends StatefulWidget{
final currentSubscription;
// Rest of the code
}
class _MyClassState extends State<MyClass> {
// Your ListView Code and other stuff.
}
This wont work when you want to change the state onTap, I recommend making the variable you use in setState within the _MyClassState class and use setState in that. Something like:
class _MyClassState extends State<MyClass> {
bool _isSelected = false;
// And in your onTap method, something like:
setState(() {
_isSelected = !_isSelected;
});
}

Flutter : Column is not support under DraggableScrollbar

this is a page of TabBarView(). I want to add some text or container(), top of the ListView.builder(). Which is scroll-able with ListView.builder(). But column() isn't supported as child of DraggableScrollbar(). Why isn't it supported it here ?
How can I add Text() or any container(), before starting ListView.builder() widget ?
import 'package:boimarket/booksdescription.dart';
import 'package:boimarket/model/model.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:draggable_scrollbar/draggable_scrollbar.dart';
class StoryBooksCategory extends StatelessWidget {
final ScrollController controller;
const StoryBooksCategory({Key key, #required this.controller})
: super(key: key);
#override
Widget build(BuildContext context) {
var _height = MediaQuery.of(context).size.height;
var _width = MediaQuery.of(context).size.width;
final Color _whiteCream = Color.fromRGBO(250, 245, 228, 1);
final Color _darkBlue = Color.fromRGBO(0, 68, 69, 1);
return Align(
alignment: Alignment.topCenter,
child: Container(
width: _width / 1.1,
child: FutureBuilder(
future: fetchBooks(),
builder: (context, AsyncSnapshot<List<Book>> snapshot) {
if (!snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
LinearProgressIndicator(
backgroundColor: _whiteCream,
),
Text("Loading"),
],
);
} else(snapshot.hasData) {
var storyBooks =
snapshot.data.where((b) => b.category == 1).toList();
storyBooks.sort((a, b) => a.name.compareTo(b.name));
print(storyBooks.length);
return DraggableScrollbar.rrect(
controller: controller,
backgroundColor: _darkBlue,
child: Column(
children: [
Text("I want to add some text here"),
ListView.builder(
controller: controller,
scrollDirection: Axis.vertical,
itemCount: storyBooks.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
Route route = MaterialPageRoute(
builder: (context) => BookDescription(
storyBooksValue: storyBooks[index]),
);
Navigator.push(context, route);
},
child: Padding(
padding: const EdgeInsets.only(
left: 10.0, right: 10.0, top: 20.0),
child: Container(
width: _width / 1.1,
height: _height / 4,
decoration: BoxDecoration(
color: _whiteCream,
borderRadius: BorderRadius.all(
Radius.circular(5.0),
),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 2,
spreadRadius: 2,
offset: Offset(2.0, 2.0),
)
],
),
),
),
),
},
),
],
),
),
},
},
),
),
),
},
}