Loading different PDF document using ListView Builder in Flutter - flutter

I am a newbie in Flutter and in programming as well.
I have created a ListView with several Cards inside each card points to separate PDF documents which are loaded using the package 'advance_pdf_viewer'. I have done all this hardcoded. But I would like to generate the Cards and the pdf document dynamically. How can I do that?
Here are my existing Codes:
Main.dart file:
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'c9Bban.dart';
import 'c9Bbanbakoron.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'HSC Textbooks',
theme: ThemeData(
primarySwatch: Colors.cyan,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'১ম - ১০ম শ্রেণী পাঠ্যবই',
style: TextStyle(
//fontSize: 14,
fontFamily: 'Baloo Da',
),
),
centerTitle: true,
),
body: ListView(children: [
Card(
child: Row(children: <Widget>[
Expanded(
flex: 8, // 20%
child: Container(
child: ListTile(
leading: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: 44,
maxHeight: 44,
),
child: Image.asset('images/bangla bakaron.jpg',
fit: BoxFit.cover),
),
title: Text(
'বাংলা ব্যাকরণ',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
fontFamily: 'Baloo da',
),
),
subtitle: Text(
'জাতীয় শিক্ষাক্রম ও পাঠ্যপুস্তক বোর্ড',
style: TextStyle(
fontSize: 12,
fontFamily: 'Baloo da',
),
),
),
),
),
Expanded(
flex: 4, // 20%
child: GestureDetector(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => C9Bbanbakoron()));
},
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300])),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(FontAwesomeIcons.book, color: Colors.green),
SizedBox(height: 5),
Text('বাংলা ও ইংরেজি ভার্সন',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14,
)),
],
),
),
),
),
]),
),
Card(
child: Row(children: <Widget>[
Expanded(
flex: 8, // 20%
child: Container(
child: ListTile(
leading: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: 44,
maxHeight: 44,
),
child: Image.asset('images/BGS.jpg', fit: BoxFit.cover),
),
title: Text(
'বাংলাদেশ ও বিশ্বপরিচয়',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
fontFamily: 'Baloo da',
),
),
subtitle: Text(
'জাতীয় শিক্ষাক্রম ও পাঠ্যপুস্তক বোর্ড',
style: TextStyle(
fontSize: 12,
fontFamily: 'Baloo da',
),
),
),
),
),
Expanded(
flex: 2, // 20%
child: GestureDetector(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => C9Bbgs()));
},
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300])
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(FontAwesomeIcons.book, color: Colors.green),
SizedBox(height: 5),
Text('বাংলা ভার্সন',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14,
)
),
],
),
),
),
),
Expanded(
flex: 2, // 20%
child: GestureDetector(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => C9Ebgs()));
},
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300])
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(FontAwesomeIcons.book, color: Colors.green),
SizedBox(height: 5),
Text('ইংরেজি ভার্সন',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14,
)
),
],
),
),
),
),
]),
),
]),
);
}
}
c9Bban.dart file (one of the separate files for loading separate PDF documents. Rest of the files are exactly the same except the PDF URL is different):
import 'package:flutter/material.dart';
import 'package:advance_pdf_viewer/advance_pdf_viewer.dart';
class C9Bban extends StatefulWidget {
#override
_MyC9Bban createState() => _MyC9Bban();
}
class _MyC9Bban extends State<C9Bban> {
bool _isLoading = true;
PDFDocument document;
#override
void initState() {
super.initState();
loadDocument();
}
loadDocument() async {
document = await PDFDocument.fromURL('https://storage.googleapis.com/school_books/Class9/ban/Bangla%20Sahitto.pdf');
setState(() => _isLoading = false);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
toolbarHeight: 20,
),
body: Center(
child: _isLoading
? Center(child: CircularProgressIndicator())
: PDFViewer(
document: document,
zoomSteps: 1,
),
),
bottomNavigationBar: BottomAppBar(
child: Container(
height: 85.0,
),
),
),
);
}
}
So far I was able to create this which works for creating the ListView Cards dynamically.
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:advance_pdf_viewer/advance_pdf_viewer.dart';
import 'c9Bban.dart';
import 'c9Bbansohopath.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'HSC Textbooks',
theme: ThemeData(
primarySwatch: Colors.cyan,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
List booklist = [
Books(
image: 'Bangla.jpg',
bookname: 'Bangla',
banbookname: 'C9Bban',
),
Books(
image: 'bangla shapath.jpg',
bookname: 'Bangla Sahapath',
banbookname: 'C9Bbansohopath',
),
];
void updateBook(index) {
Navigator.push(context, MaterialPageRoute(builder: (context) => booklist[index].banbookname));
}
return Scaffold(
appBar: AppBar(
title: Text('Book App'),
centerTitle: true,
),
body: ListView.builder(
itemCount: booklist.length,
itemBuilder: (context, index) {
return Card(
child: Row(children: <Widget>[
Expanded(
flex: 8, // 20%
child: Container(
child: ListTile(
leading: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: 44,
maxHeight: 44,
),
child:
Image.asset('images/islam.jpg', fit: BoxFit.cover),
),
title: Text(
booklist[index].bookname,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
fontFamily: 'Baloo da',
),
),
subtitle: Text(
'জাতীয় শিক্ষাক্রম ও পাঠ্যপুস্তক বোর্ড',
style: TextStyle(
fontSize: 12,
fontFamily: 'Baloo da',
),
),
),
),
),
Expanded(
flex: 2, // 20%
child: GestureDetector(
onTap: () {
updateBook(index);
},
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300])),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(FontAwesomeIcons.book, color: Colors.green),
SizedBox(height: 5),
Text('বাংলা ভার্সন',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14,
)),
],
),
),
),
),
Expanded(
flex: 2, // 20%
child: GestureDetector(
onTap: () {
updateBook(index);
},
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300])),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(FontAwesomeIcons.book, color: Colors.green),
SizedBox(height: 5),
Text('ইংরেজি ভার্সন',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14,
)),
],
),
),
),
),
]),
);
}),
);
}
}
class Books {
String image;
String bookname;
String banbookname;
String engbook;
Books({this.image, this.bookname, this.banbookname});
}

Related

Exception has occurred. StateError (Bad state: field does not exist within the DocumentSnapshotPlatform)

I have tried to build a fire store based app it have a bottom navigation bar and fetching data using StreamBuilder, but it always giving me error "Exception has occurred. StateError (Bad state: field does not exist within the DocumentSnapshotPlatform)" , what will be the solution?
The fields names are correct and some of the data is getting loaded into the ListView and after that a red screen is showing with same error message.
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following StateError was thrown building:
Bad state: field does not exist within the DocumentSnapshotPlatform
Bad state: field does not exist within the DocumentSnapshotPlatform
import 'package:eduapp/loginPage.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:get/get.dart';
import 'dart:async';
final _classStream =
FirebaseFirestore.instance.collection("classes").snapshots();
bool isInitialized = false;
signOut() async => await FirebaseAuth.instance.signOut();
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return const GetMaterialApp(
home: loginPage(),
);
}
}
class MainApp extends StatefulWidget {
const MainApp({super.key});
#override
State<MainApp> createState() => _MainAppState();
}
class _MainAppState extends State<MainApp> {
int _selectedIndex = 0;
TextStyle optionStyle =
const TextStyle(fontSize: 30, fontWeight: FontWeight.w900);
final dynamic _widgetOptions = <Widget>[
//////////////////////////////////////////////////////////////////////////////////////////////// HOME
Column(
children: [
Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.fromLTRB(40, 100, 200, 0),
child: const SizedBox(
child: Text(
"HELLO",
style: TextStyle(
fontFamily: 'Segoe',
fontSize: 50,
fontWeight: FontWeight.w800),
),
)),
Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.fromLTRB(40, 0, 040, 100),
child: const SizedBox(
child: Text(
"admin",
style: TextStyle(
fontFamily: 'Segoe',
fontSize: 24,
fontWeight: FontWeight.w400),
))),
Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.fromLTRB(40, 100, 0, 20),
child: Row(
children: const [
Text(
"Notices",
style: TextStyle(
fontFamily: 'Segoe',
fontSize: 30,
fontWeight: FontWeight.w600,
color: Colors.black),
),
Icon(
Icons.notifications,
size: 30,
)
],
)),
Expanded(
/////////////////////notices list
child: StreamBuilder(
stream:
FirebaseFirestore.instance.collection("notices").snapshots(),
builder: (context, snapshot) {
return !snapshot.hasData
? Container(
alignment: Alignment.center,
child: const SizedBox(
height: 100,
width: 100,
child: CircularProgressIndicator()))
: ListView.builder(
itemExtent: 80.0,
padding: const EdgeInsets.all(8),
itemCount: snapshot.data?.docs.length,
itemBuilder: (BuildContext context, index) =>
_noticeList(context, snapshot.data!.docs[index]));
},
),
)
],
),
///////////////////////////////////////////////////////////////////CLASSES
Column(
children: [
Expanded(
child: StreamBuilder<QuerySnapshot>(
stream: _classStream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Container(
alignment: Alignment.center,
child: const CircularProgressIndicator());
} else if (!snapshot.hasData) {
return Container(
alignment: Alignment.center,
child: const CircularProgressIndicator());
} else {
return ListView.builder(
padding: const EdgeInsets.all(10),
itemCount: snapshot.data?.docs.length,
itemBuilder: (BuildContext context, index) =>
_classesList(context, snapshot.data!.docs[index]));
}
},
),
)
],
),
////////////////////////////////////////////////////////////////////ABOUT
Column(
children: <Widget>[
SizedBox(
height: 400,
width: double.infinity,
child: ListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
children: [
Container(
alignment: Alignment.topCenter,
child: Row(
children: const [
Image(image: AssetImage("assets/icons/academy1.png")),
Image(image: AssetImage("assets/icons/academy2.png")),
Image(image: AssetImage("assets/icons/academy3.png"))
],
),
),
],
),
),
const Text(
"Institute Information\n------\n--\n\n\n Contact us \n\nPh : +91 xxx xxx xxxx\n"),
Align(
alignment: Alignment.bottomCenter,
child: ElevatedButton(
child: const Text("LogOut"),
onPressed: () {
signOut();
Get.off(const loginPage());
}),
),
],
),
];
////////////////////////////////////////////////////////////////////////////////////////////////////
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
void initState() {
_classStream;
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
backgroundColor: const Color.fromARGB(225, 85, 0, 225),
iconSize: 30,
elevation: 10,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(
Icons.home,
size: 30,
),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(
Icons.school,
size: 30,
),
label: 'Classes',
),
BottomNavigationBarItem(
icon: Icon(
Icons.account_circle,
size: 30,
),
label: 'About',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.white,
onTap: _onItemTapped,
),
);
}
}
/////////////////////////////////////////////////////////////////////////
Widget _noticeList(BuildContext context, DocumentSnapshot docs) {
return ListTile(
title: Row(
children: [
Expanded(
child: Card(
color: const Color.fromARGB(255, 255, 199, 15),
child: Container(
padding: const EdgeInsets.all(10),
alignment: Alignment.centerLeft,
height: 100,
child: Text(
docs['note'].toString(),
style: const TextStyle(
fontFamily: 'sf',
fontSize: 16,
fontWeight: FontWeight.w400,
color: Colors.black),
)),
))
],
),
);
}
//////////////////////
Widget _classesList(BuildContext context, DocumentSnapshot classdocs) {
return ListTile(
title: Row(
children: [
Expanded(
child: Card(
elevation: 20,
color: const Color.fromARGB(255, 255, 255, 255),
child: Column(
children: [
Container(
padding: const EdgeInsets.all(10),
alignment: Alignment.topLeft,
height: 50,
child: Text(
classdocs["heading"].toString(),
style: const TextStyle(
fontFamily: 'sf',
fontSize: 24,
fontWeight: FontWeight.w500,
color: Colors.black),
)),
Container(
padding: const EdgeInsets.all(10),
alignment: Alignment.topLeft,
height: 50,
child: Text(
classdocs["description"].toString(),
style: const TextStyle(
fontFamily: 'sf',
fontSize: 14,
fontStyle: FontStyle.italic,
fontWeight: FontWeight.w300,
color: Colors.black),
)),
Container(
padding: const EdgeInsets.all(10),
alignment: Alignment.topLeft,
height: 50,
child: ElevatedButton(
onPressed: () {},
child: const Text("Watch Now"),
)),
],
),
))
],
),
);
}
/////////////////////
The _noticeList in the code is working perfectly but why the _classesList giving me the error?
( _classesList is rendering some data and after that is is giving the error)

The named parameter 'body' isn't defined. in flutter code

I'm practising this code github to add a home screen with cards as pictures shown below. after the get started button clicks it should redirect to the home page with cards. cards are not still designed like the picture shows. the code I used to get cards is not working. can someone know how to fix this? no errors on main. dart. error is in home_page.dart. think I'm missing some codes.
error shows ----> Missing concrete implementation of 'StatefulWidget.createState'.
home_page.dart
import 'package:flutter/material.dart';
import 'package:fashion_app/color_filters.dart';
class HomePage extends StatefulWidget{
#override
_HomePageState createSatate ()=> _HomePageState();
}
class _HomePageState extends State <HomePage> {
final double _borderRadious = 24;
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Fashion store'),
),
body: ListView(
padding: EdgeInsets.all(16),
children: [
buildQuoteCard(),
buildRoundedCard(),
buildColoredCard(),
buildImageCard(),
buildImageInteractionCard(),
],
),
)
);
}
Widget buildQuoteCard() =>
Card(
child: Padding(
padding: EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'If life were predictable it would cease to be life,
and be without flavor.',
style: TextStyle(fontSize: 24),
),
const SizedBox(height: 12),
Text(
'Eleanor Roosevelt',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
],
),
),
);
Widget buildRoundedCard() =>
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
child: Container(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Rounded card',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
'This card is rounded',
style: TextStyle(fontSize: 20),
),
],
),
),
);
Widget buildColoredCard() =>
Card(
shadowColor: Colors.red,
elevation: 8,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.redAccent, Colors.red],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Colored card',
style: TextStyle(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
'This card is rounded and has a gradient',
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
],
),
),
);
Widget buildImageCard() =>
Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
child: Stack(
alignment: Alignment.center,
children: [
Ink.image(
image: NetworkImage(
'https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1327&q=80',
),
colorFilter: ColorFilters.greyscale,
child: InkWell(
onTap: () {},
),
height: 240,
fit: BoxFit.cover,
),
Text(
'Card With Splash',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 24,
),
),
],
),
);
Widget buildImageInteractionCard() =>
Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
child: Column(
children: [
Stack(
children: [
Ink.image(
image: NetworkImage(
'https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1327&q=80',
),
height: 240,
fit: BoxFit.cover,
),
Positioned(
bottom: 16,
right: 16,
left: 16,
child: Text(
'Cats rule the world!',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 24,
),
),
),
],
),
Padding(
padding: EdgeInsets.all(16).copyWith(bottom: 0),
child: Text(
'The cat is the only domesticated species in the family Felidae and is often referred to as the domestic cat to distinguish it from the wild members of the family.',
style: TextStyle(fontSize: 16),
),
),
ButtonBar(
alignment: MainAxisAlignment.start,
children: [
FlatButton(
child: Text('Buy Cat'),
onPressed: () {},
),
FlatButton(
child: Text('Buy Cat Food'),
onPressed: () {},
)
],
)
],
),
);
}
> main. dart
import 'package:flutter/material.dart';
import 'constants.dart';
import 'home_page.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Auth Screen 1',
theme: ThemeData(
brightness: Brightness.light,
primaryColor: kPrimaryColor,
scaffoldBackgroundColor: kBackgroundColor,
textTheme: TextTheme(
headline4: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
button: TextStyle(color: kPrimaryColor),
headline6: TextStyle(color: Colors.white70, fontWeight: FontWeight.normal),
),
inputDecorationTheme: InputDecorationTheme(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.white.withOpacity(.2),
),
),
),
),
home: WelcomeScreen(),
);
}
}
class WelcomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0XFFd5ae48),
body: Column(
children: <Widget>[
Expanded(
child: Container(
height: MediaQuery.of(context).size.height*.4,
padding: EdgeInsets.all(10.0),
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/girl.png"),
fit: BoxFit.cover,
),
),
),
flex: 3,
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
RichText(
textAlign: TextAlign.left,
text: TextSpan(
children: [
TextSpan(
text: "Let Your Styles Speaks\n",
style: Theme.of(context).textTheme.headline4,
),
TextSpan(
text: "Discover the latest trends in women fashion and explore your personality\n",
style: Theme.of(context).textTheme.headline6,
)
],
),
),
FittedBox(
child: GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) {
return HomePage();
},
));
},
child: Container(
margin: EdgeInsets.only(bottom: 25),
padding: EdgeInsets.symmetric(horizontal: 26, vertical: 16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
color: Colors.black,
),
child: Row(
children: <Widget>[
Text(
"Get started",
style: Theme.of(context).textTheme.button?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20
),
),
SizedBox(width: 10),
Icon(
Icons.arrow_forward,
color: Colors.white,
)
],
),
),
),
),
],
),
),
],
),
);
}
}
https://api.flutter.dev/flutter/widgets/StatefulWidget/createState.html
Change this,
class HomePage extends StatefulWidget{
#override
_HomePageState createSatate ()=> _HomePageState(); // change createSatate to createState
}
To,
class HomePage extends StatefulWidget{
#override
_HomePageState createState ()=> _HomePageState();
}
class HomePage extends StatefulWidget{
#override
_HomePageState createSatate ()=> _HomePageState();
}
It's because of a typo.
Change createSatate to createState.
Your Homepage class will look like
class HomePage extends StatefulWidget{
#override
_HomePageState createState ()=> _HomePageState();
}

how to create add minus button on my product in flutter?

May I know how to create a function that displays the value and have the button remove and add to the product list? I already create an icon button for remove and add to the screen but I do not have any clues on how to use the button.
GUI on application:
my aim is to have this kind of button:
my full code for this GUI:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'CartList.dart';
import 'bottom_navi_iconW.dart';
import 'globals.dart' as globals;
class SarapanPagi extends StatefulWidget {
final List list;
final int index;
final String category;
SarapanPagi({this.index,this.list,this.category});
#override
_SarapanPagiState createState() => _SarapanPagiState();
}
class _SarapanPagiState extends State<SarapanPagi> {
Future<List> getData() async{
var url = 'http://10.0.2.2/foodsystem/breakfastlist.php';
var data = {
'product_type': globals.jenisCategory,
'product_owner': widget.list[widget.index]['restaurant_id'],
};
var response = await http.post(url, body: json.encode(data));
//final response= await http.get("http://10.0.2.2/foodsystem/getdata.php");
return json.decode(response.body);}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.black),
title: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
//Text("Restaurant's Owner Page"),
Text(widget.list[widget.index]['restaurant_name'], textAlign: TextAlign.center, style: TextStyle(fontWeight: FontWeight.w700), ),
],
),
centerTitle: false,
//automaticallyImplyLeading: false,
),
body:
Padding(
padding: const EdgeInsets.only(bottom: 0, left: 5, right: 5),
child: Column(
children: [
/*FloatingActionButton(
onPressed: (){
return showDialog(
context: context,
builder: (context){
return AlertDialog(
content: Text(
globals.jenisCategory
),
);
},
);
},
),*/
//SizedBox(height: 30,),
Container(
//decoration: BoxDecoration(border: Border.all(color: Colors.black, width: 4), borderRadius: BorderRadius.circular(15)),
height: 627,
child: FutureBuilder<List>(
future: getData(),
builder: (context, snapshot){
if(snapshot.hasError) print(snapshot.error);
return snapshot.hasData ?
ItemList(list: snapshot.data,) :
Center(child: CircularProgressIndicator(),);
},
),
),
],
),
),
bottomNavigationBar:
Container(
height: 70,
color: Colors.red,
child: BottomNavIcon(
onTap: (){
Navigator.of(context).push(new MaterialPageRoute(
builder: (BuildContext context)=> new CartListItem()),);
},
image: "troli.png",
name: "CART",
),
),
);
}
}
class ItemList extends StatelessWidget {
final List list;
ItemList({this.list});
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Container(
//color: Colors.red.shade100,
height: 627,
child: ListView.builder(
itemCount: list==null ? 0 : list.length,
itemBuilder: (context, i){
return new Container(
//decoration: BoxDecoration(border: Border.all(color: Colors.blue, width: 4), borderRadius: BorderRadius.circular(15)),
height: 250,
child: new GestureDetector(
onTap: (){},
child: new Card(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
children: [
Padding(
padding: const EdgeInsets.only(bottom : 5.0),
child: Text(list[i]["product_name"], textAlign: TextAlign.center, style: TextStyle(fontSize: 23, fontWeight: FontWeight.bold),),
),
Row(
children: [
//Text(list[i]["product_name"], textAlign: TextAlign.center, style: TextStyle(fontSize: 30),),
Padding(
padding: const EdgeInsets.all(8.0),
child: Image.asset(
"menulist/${list[i]['image']}",
width: 150,
height: 150,
),
),
Padding(
padding: const EdgeInsets.only(left: 20.0, bottom: 0),
child:
Column(
children: [
//Text(list[i]["product_name"], textAlign: TextAlign.center, style: TextStyle(fontSize: 30),),
Text("Price RM : ${list[i]["product_price"]}", textAlign: TextAlign.center, style: TextStyle(fontSize: 25),),
Row(
children: [
IconButton(
icon: Icon(Icons.remove),
onPressed: (){},
iconSize: 15,
),
IconButton(
icon: Icon(Icons.add),
onPressed: (){},
iconSize: 15,
),
],
),
RaisedButton(
shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(40.0)),
color: Colors.red.shade300,
child: Text("Add to Cart", style: TextStyle(fontWeight: FontWeight.bold),),
onPressed: (){},
)
],
),
),
],
),
],
),
/*ListTile(
title: Text(list[i]["product_name"], textAlign: TextAlign.center, style: TextStyle(fontSize: 30),),
leading:
Image.asset(
"images/${list[i]['image']}",
width: 100,
height: 100,
),
subtitle: Text("Price RM : ${list[i]["product_price"]}", textAlign: TextAlign.center, style: TextStyle(fontSize: 25),),
),*/
],
),
),
),
);
},
),
),
);
}
}
First of all you need to change it to StatefulWidget, since the UI interaction is rendered (changed price). Then something like
onPressed: () => setState(() => list[i]["product_price"] += unitprice),
will do

How to dynamically sort by date in flutter?

I am working on a to do list app on flutter and I will like to sort the uploaded tasks by date(new ones appear first). for doing this I think a key should be givin to each of the uploaded items in the to do list and this key should include a Date. In react native for doing this I added a function to the data in a flatlist which sorted by date but since I am new to flutter I dont know how can that be done. Any Idea helps :)
main.dart
List<String> _toDoItems = []; //this is the array in which the uploaded tasks are stored, btw Im not using any database.
TextEditingController _controller = TextEditingController();
void _addToDoItem(String task) {
if(task.length > 0) {
setState(() {
_toDoItems.add(task);
});
}
}
void _removeTodoItem(int index) {
setState(() => _toDoItems.removeAt(index));
}
Widget _buildToDoItem(String toDoText, int index) {
return SizedBox(
child: Container(
height: 58,
margin: EdgeInsets.only(left: 22.0, right: 22.0, bottom: 12,),
decoration: BoxDecoration(
border: Border.all(width: 1.5, color: Colors.red),
borderRadius: BorderRadius.all(Radius.circular(18)),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children:[
Expanded(
child: ListTile(
title: Text(
toDoText,
style: TextStyle(fontSize: 18),
),
onTap: () => _removeTodoItem(index),
),
),
FlatButton(
child: Text('Delete', style: TextStyle(color: Colors.red, fontSize: 16.5),),
onPressed: () => _removeTodoItem(index),
),
],
),
),
);
}
Widget _buildToDoList() {
return Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
if (index < _toDoItems.length) {
return _buildToDoItem(_toDoItems[index], index);
}
},
),
);
}
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(50),
child: AppBar(
centerTitle: true,
backgroundColor: Colors.red,
title: Text('To Do List', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold,),),
)
),
backgroundColor: Colors.white,
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 60,
margin: EdgeInsets.all(22),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
flex: 10,
child: Container(
height: double.infinity,
child: TextField(
controller: _controller,
autofocus: true,
onSubmitted: (val) {
_addToDoItem(val);
_controller.clear();
},
style: TextStyle(fontSize: 18,),
),
),
),
Expanded(
flex: 4,
child: Container(
height: double.infinity,
margin: EdgeInsets.only(left: 12),
child: RaisedButton(
textColor: Colors.white,
color: Colors.red,
child: Text('ADD', style: TextStyle(fontSize: 18)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(12)),
),
onPressed: () {
_addToDoItem(_controller.text);
_controller.clear();
FocusScope.of(context).requestFocus(FocusNode());
},
),
),
),
],
),
),
_buildToDoList()
]
),
),
);
}
You need to use the sort() method of List, also you need to be able to stock in a way or another the time of creation of your task.
I've made an example with the code you've posted. Using it your last created element will always be the first of the list.
import 'package:flutter/material.dart';
class ToDoElement {
final String task;
final DateTime timeOfCreation;
ToDoElement(this.task, this.timeOfCreation);
}
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
createState() => _MyAppState();
}
class _MyAppState extends State {
TextEditingController _controller = TextEditingController();
List<ToDoElement> _toDoItems = [];
void _removeTodoItem(int index) {
setState(() => _toDoItems.removeAt(index));
}
void _addToDoItem(String task) {
if (task.isNotEmpty) {
setState(() => _toDoItems.add(ToDoElement(task, DateTime.now())));
}
}
Widget _buildToDoItem(String toDoText, int index) {
return SizedBox(
child: Container(
height: 58,
margin: EdgeInsets.only(left: 22, right: 22, bottom: 12),
decoration: BoxDecoration(
border: Border.all(width: 1.5, color: Colors.red),
borderRadius: BorderRadius.all(Radius.circular(18)),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: ListTile(
title: Text(
toDoText,
style: TextStyle(fontSize: 18),
),
onTap: () => _removeTodoItem(index),
),
),
FlatButton(
child: Text(
'Delete',
style: TextStyle(color: Colors.red, fontSize: 16.5),
),
onPressed: () => _removeTodoItem(index),
),
],
),
),
);
}
int compareElement(ToDoElement a, ToDoElement b) =>
a.timeOfCreation.isAfter(b.timeOfCreation) ? -1 : 1;
Widget _buildToDoList() {
_toDoItems.sort(compareElement);
return Expanded(
child: ListView.builder(
itemCount: _toDoItems.length,
itemBuilder: (context, index) {
return _buildToDoItem(_toDoItems[index].task, index);
},
),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(50),
child: AppBar(
centerTitle: true,
backgroundColor: Colors.red,
title: Text(
'To Do List',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
)),
backgroundColor: Colors.white,
body: Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
Container(
height: 60,
margin: EdgeInsets.all(22),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
flex: 10,
child: Container(
height: double.infinity,
child: TextField(
controller: _controller,
autofocus: true,
onSubmitted: (val) {
_addToDoItem(val);
_controller.clear();
},
style: TextStyle(
fontSize: 18,
),
),
),
),
Expanded(
flex: 4,
child: Container(
height: double.infinity,
margin: EdgeInsets.only(left: 12),
child: RaisedButton(
textColor: Colors.white,
color: Colors.red,
child: Text('ADD', style: TextStyle(fontSize: 18)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(12)),
),
onPressed: () {
_addToDoItem(_controller.text);
_controller.clear();
FocusScope.of(context).requestFocus(FocusNode());
},
),
),
),
],
),
),
_buildToDoList()
]),
),
);
}
}

Flutter: How to set variable length string inside a row?

I am trying to set a string inside a row, but the length of the string is variable i.e data is fetched from API. Then it is set inside the row, but currently, as the length is greater it shows as A RenderFlex overflowed by 48 pixels on the right.
I am been trying to use expanded/flex/flexible but getting incorrect parent error. (Don't know how to as I am new to flutter)
So, please help in how to solve this problem of renderflex overflow.
Following is my method:
void confirmpayment(double amount, String description) {
final itemsSubmit = <Widget>[
Image.asset(
'images/payments.jpg',
width: MediaQuery.of(context).size.width,
fit: BoxFit.contain,
),
ListTile(
title: AutoSizeText(
'Confirmation',
style: TextStyle(fontSize: 20),
),
subtitle: AutoSizeText(
'Hey Gaurav, please confirm examination as payment once done will be irrevocable.',
style: TextStyle(color: Colors.grey),
),
// onTap: () {},
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 20,
),
Padding(
padding: EdgeInsets.only(top: 10),
child: AutoSizeText(
'Exam:',
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 16,
),
),
),
Spacer(),
CheckboxGroup(
orientation: GroupedButtonsOrientation.VERTICAL,
labelStyle: TextStyle(fontSize: 15),
labels: [
...listexam.map((location) {
return location['name']; //this is where string is set from api data
}).toList()
],
checked: _checked,
),
SizedBox(
width: 20,
),
],
),
Divider(),
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 20,
),
Padding(
padding: EdgeInsets.only(top: 1),
child: AutoSizeText(
'Plan',
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 16,
),
),
),
Expanded(
child: Padding(
padding: EdgeInsets.only(top: 1),
child: AutoSizeText(
description,
textAlign: TextAlign.right,
textDirection: TextDirection.ltr,
style: TextStyle(
fontSize: 15,
),
),
),
),
SizedBox(
width: 20,
),
]),
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 20,
),
Padding(
padding: EdgeInsets.only(top: 1),
child: AutoSizeText(
'Amount',
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 16,
),
)),
Expanded(
child: Padding(
padding: EdgeInsets.only(top: 1),
child: AutoSizeText(
'Rs. ' + amount.toString(),
textDirection: TextDirection.ltr,
textAlign: TextAlign.right,
style: TextStyle(
fontSize: 15,
// fontWeight: FontWeight.w500,
),
),
),
),
SizedBox(
width: 20,
),
]),
SizedBox(
height: 40,
),
Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[
RaisedButton(
elevation: 1,
// onPressed: _showSheetSubmit,
color: Colors.grey[200],
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(28.0),
side: BorderSide(color: Colors.grey[200])),
onPressed: null,
child: AutoSizeText(
"Cancel",
style: TextStyle(
fontSize: 16,
// fontFamily: 'lato',
letterSpacing: 1,
color: Colors.white,
),
)),
RaisedButton(
elevation: 1,
color: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(28.0),
side: BorderSide(color: Colors.green)),
onPressed: () {
openCheckout(amount, description);
},
child: AutoSizeText(
"Buy",
style: TextStyle(
fontSize: 16,
// fontFamily: 'lato',
color: Colors.white,
letterSpacing: 1),
)),
]),
SizedBox(
height: MediaQuery.of(context).size.height / 12,
),
];
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
backgroundColor: Colors.white,
context: context,
builder: (BuildContext _) {
return Container(
// color: Colors.white,
child: Wrap(
children: itemsSubmit,
),
);
},
isScrollControlled: true,
// isDismissible: true
);
}
Following is the mock:
Instead of trying to trim the String data that will go into the Text widget, I would use a LayoutBuilder to get the available space that the Row widget could occupy. Then, I would wrap the Text in a SizedBox to limit the maximum width of the Text widget. Finally, I would set the overflow property of the Text widget, so that it shows an ellipsis when the text is longer than the available space.
Here is a little app I wrote for you to see how to do this. You can run it on DartPad to play around with it.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
LayoutBuilder(
builder: (context, constraints) {
return Row(
children: <Widget>[
SizedBox(
width: constraints.maxWidth,
child: Text(
'This is a very very long text that might overflow the available rendering space',
overflow: TextOverflow.ellipsis,
),
),
],
);
},
),
],
),
),
);
}
}