Flutter bloc doesn't showing UI as per proper state - flutter

Am using flutter bloc library and maintaining simple process for as per library for state management. In this code I am getting the state as expected but UI is not updating, its always returning the default state ui which a circle spinner . I have checked the state using bloc observer too. So need to know that what I have done wrong and need suggestions on that.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: buildAppBar(context),
body: Column(
children: [
BlocBuilder<UserManageCubit, UserManageState>(
builder: (context, state) {
if (state is Initial) {
return const Center(
child: CircularProgressIndicator(
color: Colors.red,
));
}
if (state is UserDetailFetched) {
Column(
children: <Widget>[
Text(
'${state.userDetails.name}'.toUpperCase(),
style: kNavyTextStyleNormal.copyWith(
fontSize: 18.sp,
),
),
Text(
'${state.userDetails.email}',
style: kNavyTextStyleNormal.copyWith(
fontWeight: FontWeight.bold,
),
),
Text(
'${state.userDetails.phone}',
style: kNavyTextStyleNormal.copyWith(
fontWeight: FontWeight.bold,
),
),
Text(
'Registered on ${DateTimeUtils.format(
DateTimeUtils.fromString(state.userDetails.createdAt!),
).split("-")[0]}',
style: kNavyTextStyleNormal.copyWith(
fontWeight: FontWeight.bold,
color: go11ThemeGreen,
),
),
SizedBox(height: 16.h),
],
);
}
return CircularProgressIndicator(
color: Colors.amber,
);
},
),
],
),
);
}
Calling bloc
#override
void initState() {
BlocProvider.of<UserManageCubit>(context).getUserDetails(widget.userId);
super.initState();
}
#Cubit impl
UserManageCubit({required this.userManageRepo})
: super(const UserManageState.initial());
void getUserDetails(int userId) async {
final FormData formData = FormData.fromMap({
'user_id': userId,
});
final Either<Failure, UserDetailsResponse> userDetailResponseEither =
await userManageRepo.getUserDetails(formData);
emit(const UserManageState.loading());
userDetailResponseEither.fold(
(failure) => {
emit(
UserManageState.loadFailure(
errorObject:
ErrorObject.mapFailureToErrorObject(failure: failure),
),
)
},
(response) => {
emit(
UserManageState.userDetailFetched(
userDetails: response.userDetails),
),
});
}
#state class
#freezed
class UserManageState with _$UserManageState {
const factory UserManageState.initial() = Initial;
const factory UserManageState.loading() = Loading;
const factory UserManageState.loadFailure({
required ErrorObject errorObject,
}) = LoadFailure;
const factory UserManageState.userDetailFetched(
{required UserDetails userDetails,
#Default(0) int currentDocType,
#Default(0) int currentCancelType}) = UserDetailFetched;
}

You are not returning your column
if (state is UserDetailFetched) {
return Column(
children: <Widget>[
Text(
'${state.userDetails.name}'.toUpperCase(),
style: kNavyTextStyleNormal.copyWith(
fontSize: 18.sp,
),
),
Text(
'${state.userDetails.email}',
style: kNavyTextStyleNormal.copyWith(
fontWeight: FontWeight.bold,
),
),
Text(
'${state.userDetails.phone}',
style: kNavyTextStyleNormal.copyWith(
fontWeight: FontWeight.bold,
),
),
Text(
'Registered on ${DateTimeUtils.format(
DateTimeUtils.fromString(state.userDetails.createdAt!),
).split("-")[0]}',
style: kNavyTextStyleNormal.copyWith(
fontWeight: FontWeight.bold,
color: go11ThemeGreen,
),
),
SizedBox(height: 16.h),
],
);
}

Related

Only one List item displayed when changing screen / page

On the add Weight screen I pick a weight and a date and then it gets stored in a list in the Hive database, once I press "Save".
It also returns me to the Homepage, where I would like to depict the stored list items in a ListView.Builder.
I only get the last item on the list and not the whole list.
When I am at the add weight screen, I see that there are more items in the list, but once I return to homepage only the last one exists.
AddWeightScreen
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:intl/intl.dart';
import 'package:weighty/components/my_alert_box.dart';
import 'package:weighty/data/database.dart';
import 'package:weighty/screens/home_page.dart';
class AddWeight extends StatefulWidget {
const AddWeight({super.key});
#override
State<AddWeight> createState() => _AddWeightState();
}
class _AddWeightState extends State<AddWeight> {
Database db = Database();
final _myBox = Hive.box("mybox");
double _currentValue = 0;
DateTime _dateTime = DateTime.now();
String formattedDate = DateFormat('d MMM yyyy').format(DateTime.now());
final _weightController = TextEditingController();
void _showDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime.now(),
).then((value) {
setState(() {
_dateTime = value!;
formattedDate = DateFormat('d MMM yyyy').format(_dateTime);
});
});
}
// add weight from text - keyboard
void _dialogNumber() {
showDialog(
context: context,
builder: (context) {
return MyAlertBox(
controller: _weightController,
hintText: "Enter today's weight...",
onSave: () {
if (double.parse(_weightController.text) > 200) {
_weightController.text = "200";
}
setState(() {
_currentValue = double.parse(_weightController.text);
});
_weightController.clear();
Navigator.pop(context);
},
onCancel: cancelDialogBox);
});
}
//save method
void _saveWeightAndDate() {
setState(() {
db.weightList.add([_currentValue, formattedDate]);
});
db.saveData();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const HomePage(),
),
);
}
// cancel new weight input
void cancelDialogBox() {
// clear textfield
_weightController.clear();
// pop dialog box
Navigator.of(context).pop();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFFD9F0FF),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
const SizedBox(
height: 28.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
"Add Weight",
style: TextStyle(fontSize: 36, fontWeight: FontWeight.w600),
),
MaterialButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text(
'CANCEL',
style: TextStyle(
color: Color(0xff878472),
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
),
],
),
const SizedBox(height: 30),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
child: MaterialButton(
onPressed: _dialogNumber,
child: Text(
_currentValue.toStringAsFixed(2) + " kg",
style: TextStyle(
color: Color(0xFF006B8F),
fontSize: 46,
fontWeight: FontWeight.w500),
),
),
),
const SizedBox(height: 30),
Slider(
value: _currentValue,
min: 0,
max: 200,
onChanged: ((value) {
setState(() {
_currentValue = value;
});
}),
),
const SizedBox(height: 30),
TextButton.icon(
onPressed: _showDatePicker,
icon: const Icon(
Icons.date_range_outlined,
size: 24.0,
color: Color(0xff878472),
),
label: Text(
formattedDate,
style: TextStyle(color: Color(0xff878472), fontSize: 18),
),
),
const SizedBox(height: 30),
ElevatedButton(
onPressed: _saveWeightAndDate,
child: Text(
'SAVE',
style:
TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
style: ElevatedButton.styleFrom(
elevation: 24,
padding:
EdgeInsets.symmetric(vertical: 20, horizontal: 80),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
side: BorderSide(color: Colors.white, width: 2),
),
),
),
const SizedBox(height: 30),
],
),
),
],
),
),
);
}
}
HomePage
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:weighty/components/weight_tile.dart';
import 'package:weighty/data/database.dart';
import 'package:weighty/main.dart';
import 'package:weighty/screens/add_weight.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
void initState() {
//First time ever opening app, Create default data
// if (_myBox.get("WEIGHTLIST") == null) {
// }
//already exists data
db.loadData();
// db.saveData();
super.initState();
}
Database db = Database();
final _myBox = Hive.box("mybox");
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[100],
floatingActionButton: FloatingActionButton(
backgroundColor: Color(0xff006B8F),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const AddWeight(),
),
);
},
child: const Icon(Icons.add),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 28),
Text(
"CURRENT",
style: TextStyle(
color: Colors.grey[500],
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
Text(
db.weightList.length == 0
? "00.0 Kg"
: db.weightList.last[0].toStringAsFixed(2) + " kg",
style: TextStyle(
color: Color(0xFF006B8F),
fontSize: 46.0,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 40),
Center(
child: Text(
"GRAPH",
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
),
Expanded(
child: ListView.builder(
itemCount: db.weightList.length,
itemBuilder: (context, index) {
return WeightTile(
date: db.weightList[index][1],
weight: db.weightList[index][0].toStringAsFixed(2),
);
},
),
),
ElevatedButton(
onPressed: () {
print(db.weightList.length);
},
child: Text('Print!')),
],
),
),
);
}
}
Hive Database
import 'package:hive_flutter/hive_flutter.dart';
class Database {
//reference the box
final _myBox = Hive.box("mybox");
// Empty Weight List
List weightList = [];
// void createInitialData() {
// weightList = [];
// }
//load the date from the db
void loadData() {
weightList = _myBox.get("WEIGHTLIST");
}
//save the weight
void saveData() {
_myBox.put("WEIGHTLIST", weightList);
}
}
I could not rebuild your project to debug it. so I'm kind of taking a shot in the darkness.
there is a widget called valuelistenablebuilder which gets rebuilt when ever a value changes you can set your box to the value being listened by this widget and rebuild every time a new value is added to your box you can find an example on this page
For whole list you have to first get old list which is saved in hive then sum this list and save in to hive
Output is
For you example you have to update saveData method in to a Database class
void saveData() {
final myBox = Hive.box("mybox");
List? hiveList = [];
hiveList = myBox.get("WEIGHTLIST") ?? [];
if (hiveList!.isNotEmpty) {
hiveList += weightList;
} else {
hiveList = weightList;
}
_myBox.put("WEIGHTLIST", hiveList);
}
You will be get whole list into a homescreen

Initializing an input in a form for submission

I am trying to send an API post through my flutter app:
The user inserts the log_weight through a textfield which inside table inside a Form. The row of the table are iterations from a list.
In my flutter app I have created a table that iterates through a list inside a form. So I am trying to get a log submission from each iteration.
Here is my api_serice.dart:
class APIService {
static var client = http.Client();
Future<http.Response> addLog(
int logWeight) async {
var url = Uri.parse(Config.apiURL +
Config.userAddlogAPI);
final response = await http.post(url, headers: {
HttpHeaders.authorizationHeader:
'Token xxxxxxxxxxxxxxxxxx',
}, body: {
'log_weight': logWeight,
});
}
Here is the exercises.dart:
class Exercises extends StatefulWidget {
#override
_ExercisesState createState() => _ExercisesState();
}
class _ExercisesState extends State<Exercises> {
late Map<String, int> arguments;
late int logWeight;
Here is the form:
Builder(builder: (context) {
return Form(
key: key,
child: Table(
children: [
const TableRow(children: [
Text(
'',
style: TextStyle(
fontSize: 15,
fontWeight:
FontWeight.bold,
color: Colors.black,
),
),
Text(
'Weight',
style: TextStyle(
fontSize: 15,
fontWeight:
FontWeight.bold,
color: Colors.black,
),
),
Text(
'New Weight',
style: TextStyle(
fontSize: 15,
fontWeight:
FontWeight.bold,
color: Colors.black,
),
),
Text(
'Submit',
style: TextStyle(
fontSize: 15,
fontWeight:
FontWeight.bold,
color: Colors.black,
),
)
]),
// Iterate over the breakdowns list and display the sequence information
for (var breakdown in snapshot
.data![index].breakdowns)
TableRow(children: [
Text(
'${breakdown.order}',
style: const TextStyle(
fontSize: 15,
color: Colors.black,
),
),
Text(
'${breakdown.weight}',
style: const TextStyle(
fontSize: 15,
color: Colors.black,
),
),
TextFormField(
decoration:
InputDecoration(
border:
InputBorder.none,
),
style: const TextStyle(
fontSize: 15,
color: Colors.black,
),
validator: (value) {
if (value == null) {
return 'Please enter a valid number';
}
return null;
},
onSaved: (value) {
logWeight =
int.parse(value!);
},
),
OutlinedButton(
onPressed: () async {
final Map<String, int>
arguments =
ModalRoute.of(
context)!
.settings
.arguments
as Map<String,
int>;
final int id =
arguments['id'] ??
0;
try {
if (Form.of(context)
?.validate() ==
true) {
Form.of(context)
?.save();
APIService.addLog(
id,
logWeight);
}
} catch (error) {
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text(
'Error'),
content: Text(error
.toString()),
actions: [
OutlinedButton(
child: Text(
'OK'),
onPressed:
() {
Navigator.of(
context)
.pop();
}, ),],);},);}},
child: Text('Submit'),
),]),],),);
How can I fix my code so that I can send the log_weight. I keep getting E/flutter ( 4353): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: LateInitializationError: Field 'logWeight' has not been initialized.
The error is caused by late keyword. variables that are late must be initialized. Try not to use late that much.
Solution 1. make logWeight non-nullable and initialize it. Because your addLog method only allows non-nullable logWeight value.
int logWeight = 0;
Solution 2. make logWeight nullable and before calling the api, check if it's null or not. (If logWeight is required param for your api)
int? logWeight;
---
if(logWeight != null) {
APIService.addLog(id,logWeight);
}
or use validation
Solution 3. (If logWeight is not required param for your api) just make logWeight nullable and change your method to allow nullable logWeight value
int? logWeight;
---
class APIService {
static var client = http.Client();
Future<http.Response> addLog(
int? logWeight) async {
...
}

how to Activate Elevatedbutton when checkboxListTile is selected

I'm making a page of terms and conditions.
I'm using checkboxListTile.
enter image description here
However, the Elevated Button shall be activated when selecting all items from the first to fifth items of the termsAndConditions.
The last sixth item may or may not be selected.
Otherwise, Elevated Button is disabled and the color should appear gray.
enter image description here
and Elevated Button must be activated when alltermsAndConditions are selected.
enter image description here
It’s too difficult.
Is there a solution?
I'd like to thank the people who answer.
class TermsAgreementPage extends StatelessWidget {
TermsAgreementPage({
Key? key,
}) : super(key: key);
CheckBoxState checkBoxState = Get.put(CheckBoxState(title: '', subTitle: ''));
final alltermsAndConditions = CheckBoxState(title: '전체동의', subTitle: '');
final termsAndConditions = [
CheckBoxState(
title: '이용 약관 동의(필수)',
subTitle: '니어엑스 서비스 이용 통합 약관입니다.'),
CheckBoxState(
title: '개인정보 처리방침 동의(필수)',
subTitle: '개인정보보호 포털 법률에 의거한 제공동의로 필수 사항입니다.'),
CheckBoxState(
title: '개인정보 제3자 제공동의(필수)',
subTitle: '개인정보보호 포털 법률에 의거한 제공 동의로 필수 사항입니다.'),
CheckBoxState(
title: '위치기반 서비스 이용약관(필수)',
subTitle: '주변 가게들 검색에 사용됩니다.'),
CheckBoxState(
title: '전자금융거래 이용약관(필수)',
subTitle: '구매 또는 결제 사항이 있을 경우 제공 동의로 필수 사항입니다.'),
CheckBoxState(
title: '니어엑스 혜택 알림 동의(선택)',
subTitle: '미선택 시 주변가게 할인 및 만기 다가오는 쿠폰 알림 사용 불가.'),
];
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
body: Padding(
padding: const EdgeInsets.only(top: 80.0, bottom: 40),
child: Column(
children: [
Expanded(
flex: 1,
child: Container(
width: size.width,
child: Column(
children: const [
Text(
'이용 약관 동의',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
Text(
'아래의 약관에 동의 하신 후 서비스를 이용해 주시기 바랍니다.',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: Colors.grey),
),
],
),
),
),
Expanded(
flex: 6,
child: Obx(
() => ListView(
children: [
buildGroupCheckbox(
CheckBoxState(title: '전체동의', subTitle: '')),
const Divider(color: Colors.grey, height: 2),
...termsAndConditions.map(buildCheckbox).toList()
],
),
),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
padding:
const EdgeInsets.symmetric(horizontal: 50, vertical: 10),
textStyle: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w400,
color: Colors.white)),
onPressed: () {
},
child: const Text('시작하기'),
),
],
),
),
);
}
Widget buildGroupCheckbox(CheckBoxState checkBoxState) {
return CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
secondary: TextButton(
onPressed: () {
Get.toNamed('/home');
},
child: const Text(
'전문보기',
style: TextStyle(fontSize: 10.0, color: Colors.blue),
)),
title: Text(
checkBoxState.title,
style: const TextStyle(fontSize: 12),
),
subtitle: Text(
checkBoxState.subTitle,
style: const TextStyle(fontSize: 9, color: Colors.grey),
),
onChanged: toggleCheckBox,
value: alltermsAndConditions.isChecked.value,
);
}
void toggleCheckBox(bool? value) {
if (value == null) return;
alltermsAndConditions.isChecked.value = value;
for (var termsAndConditions in termsAndConditions) {
termsAndConditions.isChecked.value = value;
}
}
Widget buildCheckbox(CheckBoxState checkBoxState) {
return CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
// 왼쪽에 네모 박스 위치
title: Text(
checkBoxState.title,
style: const TextStyle(fontSize: 12),
),
subtitle: Text(
checkBoxState.subTitle,
style: const TextStyle(fontSize: 9, color: Colors.grey),
),
onChanged: (value) {
checkBoxState.isChecked.value = value!;
alltermsAndConditions.isChecked.value = termsAndConditions.every(
(termsAndConditions) => termsAndConditions.isChecked.value);
},
value: checkBoxState
.isChecked.value
);
}
}
********** controller **********
class CheckBoxState extends GetxController {
RxBool isChecked = false.obs;
final String title; // CheckBoxListTile 의 타이틀 제목
final String subTitle; // CheckBoxListTile 의 서브타이틀 내용
CheckBoxState({
required this.title,
required this.subTitle,
});
}
enter code here
First of all you should change this line :
termsAndConditions.map(buildCheckbox).toList()
to this :
termsAndConditions.asMap().forEach((key, value) {
buildCheckbox(value,key);
});
//or if this does work you add .toList()
termsAndConditions.asMap().forEach((key, value) {
buildCheckbox(value,key);
}).toList();
then you change the buildCheckbox function to include the key/index of the list you are passing
Widget buildGroupCheckbox(CheckBoxState checkBoxState,int index) {
...
}
then you need to add an array of booleans to keep track of the checkboxes
final checkBoxState= [false,false,false,false,false,false];
now you are implementing something like this :
onChanged: (value) {
//new code
if (value){checkBoxState[index]=true;}
else {checkBoxState[index]=false;}
checkBoxState.isChecked.value = value!;
alltermsAndConditions.isChecked.value = termsAndConditions.every(
(termsAndConditions) => termsAndConditions.isChecked.value);
},
Finally you can each individual checkbox statue and can do anything you want :
onPressed: (!sumof5first())?null:() {
//does something
},
}
bool sumof5first(){
int sum = 0;
for (int i=0;i<5;i++){
if (checkBoxState[i]==true){sum++}
}
if (sum>4){return true}
else {return false}
}

How to Remove cart item using provider

I am using provider class in which i can add items to the cart list using product id but when i use the similar function to remove the item from cart it seems the function dont find the product id.or im doing somting wrong.
The function i used to add items in provider class:
//---------------------------------------add item
void addItem({
required CartItem product,
}) {
if (items.containsKey(product.id)) {
final double value = product.price;
items.update(
product.id,
(cartitem) => cartitem.copy(
qnt: cartitem.qnt + 1,
price: cartitem.price + value,
),
);
} else {
items.putIfAbsent(
product.id,
() => product.copy(
id: DateTime.now().toString(),
qnt: 1,
));
}
//---------------------------------------------------------total price
_totalPrice = _totalPrice + product.price;
notifyListeners();
}
and the list in my cart:
//----------- items cart list
Widget buildCarditems(BuildContext context) {
final porvidr = Provider.of<ShopProvider>(context, listen: false);
if (porvidr.items.isEmpty) {
return Center(
child: Text(
'Cart is Empty',
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
);
} else {
return ListView(
children: porvidr.items.values.map(buildcarditem).toList(),
);
}
}
//------------cart listtile
Widget buildcarditem(CartItem c_item) {
return ListTile(
leading: CircleAvatar(backgroundImage: AssetImage(c_item.imgUrl)),
title: Row(
children: [
Text(
'${c_item.qnt}x',
style: TextStyle(color: Colors.white),
),
SizedBox(
width: 10,
),
Expanded(
child: Text(
c_item.title,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
),
],
),
trailing: Text(
'\$${c_item.price}',
style: TextStyle(
color: Colors.white,
),
));
}
where can i use the ontap function to get the product id?
You can add it anywhere you want on each list item, you can wrap the list tile in n gesture detector widget. it depends on the requirement.

Null check operator used on a null value Carousel Flutter

Good Morning,
I'm trying to put a Carousel on the home page looking for Firebase data, but for some reason, the first time I load the application it appears the message below:
════════ Exception caught by widgets library ═════════════════════════════════════ ══════════════════
The following _CastError was thrown building DotsIndicator (animation: PageController # 734f9 (one client, offset 0.0), dirty, state: _AnimatedState # 636ca):
Null check operator used on a null value
and the screen looks like this:
After giving a hot reload the error continues to appear, but the image is loaded successfully, any tips of what I can do?
HomeManager:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provantagens_app/models/section.dart';
class HomeManager extends ChangeNotifier{
HomeManager({this.images}){
_loadSections();
images = images ?? [];
}
void addSection(Section section){
_editingSections.add(section);
notifyListeners();
}
final List<dynamic> _sections = [];
List<String> images;
List<dynamic> newImages;
List<dynamic> _editingSections = [];
bool editing = false;
bool loading = false;
int index, totalItems;
final Firestore firestore = Firestore.instance;
Future<void> _loadSections() async{
loading = true;
firestore.collection('home').snapshots().listen((snapshot){
_sections.clear();
for(final DocumentSnapshot document in snapshot.documents){
_sections.add( Section.fromDocument(document));
images = List<String>.from(document.data['images'] as List<dynamic>);
}
});
loading = false;
notifyListeners();
}
List<dynamic> get sections {
if(editing)
return _editingSections;
else
return _sections;
}
void enterEditing({Section section}){
editing = true;
_editingSections = _sections.map((s) => s.clone()).toList();
defineIndex(section: section);
notifyListeners();
}
void saveEditing() async{
bool valid = true;
for(final section in _editingSections){
if(!section.valid()) valid = false;
}
if(!valid) return;
loading = true;
notifyListeners();
for(final section in _editingSections){
await section.save();
}
for(final section in List.from(_sections)){
if(!_editingSections.any((s) => s.id == section.id)){
await section.delete();
}
}
loading = false;
editing = false;
notifyListeners();
}
void discardEditing(){
editing = false;
notifyListeners();
}
void removeSection(Section section){
_editingSections.remove(section);
notifyListeners();
}
void onMoveUp(Section section){
int index = _editingSections.indexOf(section);
if(index != 0) {
_editingSections.remove(section);
_editingSections.insert(index - 1, section);
index = _editingSections.indexOf(section);
}
notifyListeners();
}
HomeManager clone(){
return HomeManager(
images: List.from(images),
);
}
void onMoveDown(Section section){
index = _editingSections.indexOf(section);
totalItems = _editingSections.length;
if(index < totalItems - 1){
_editingSections.remove(section);
_editingSections.insert(index + 1, section);
index = _editingSections.indexOf(section);
}else{
}
notifyListeners();
}
void defineIndex({Section section}){
index = _editingSections.indexOf(section);
totalItems = _editingSections.length;
notifyListeners();
}
}
HomeScreen:
import 'package:carousel_pro/carousel_pro.dart';
import 'package:flutter/material.dart';
import 'package:provantagens_app/commom/custom_drawer.dart';
import 'package:provantagens_app/commom/custom_icons_icons.dart';
import 'package:provantagens_app/models/home_manager.dart';
import 'package:provantagens_app/models/section.dart';
import 'package:provantagens_app/screens/home/components/home_carousel.dart';
import 'package:provantagens_app/screens/home/components/menu_icon_tile.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
// ignore: must_be_immutable
class HomeScreen extends StatelessWidget {
HomeManager homeManager;
Section section;
List<Widget> get children => null;
String videoUrl = 'https://www.youtube.com/watch?v=VFnDo3JUzjs';
int index;
var _tapPosition;
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(colors: const [
Colors.white,
Colors.white,
], begin: Alignment.topCenter, end: Alignment.bottomCenter)),
child: Scaffold(
backgroundColor: Colors.transparent,
drawer: CustomDrawer(),
appBar: AppBar(
backgroundColor: Colors.transparent,
iconTheme: IconThemeData(color: Colors.black),
title: Text('Página inicial', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8))),
centerTitle: true,
actions: <Widget>[
Divider(),
],
),
body: Consumer<HomeManager>(
builder: (_, homeManager, __){
return ListView(children: <Widget>[
AspectRatio(
aspectRatio: 1,
child:HomeCarousel(homeManager),
),
Column(
children: <Widget>[
Container(
height: 50,
),
Divider(
color: Colors.black,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Padding(
padding: const EdgeInsets.only(left:12.0),
child: MenuIconTile(title: 'Parceiros', iconData: Icons.apartment, page: 1,),
),
Padding(
padding: const EdgeInsets.only(left:7.0),
child: MenuIconTile(title: 'Beneficios', iconData: Icons.card_giftcard, page: 2,),
),
Padding(
padding: const EdgeInsets.only(right:3.0),
child: MenuIconTile(title: 'Suporte', iconData: Icons.help_outline, page: 6,),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
MenuIconTile(iconData: Icons.assignment,
title: 'Dados pessoais',
page: 3)
,
MenuIconTile(iconData: Icons.credit_card_outlined,
title: 'Meu cartão',
page: 4)
,
MenuIconTile(iconData: Icons.account_balance_wallet_outlined,
title: 'Pagamento',
page: 5,)
,
],
),
Divider(
color: Colors.black,
),
Container(
height: 50,
),
Consumer<HomeManager>(
builder: (_, sec, __){
return RaisedButton(
child: Text('Teste'),
onPressed: (){
Navigator.of(context)
.pushReplacementNamed('/teste',
arguments: sec);
},
);
},
),
Text('Saiba onde usar o seu', style: TextStyle(color: Colors.black, fontSize: 20),),
Text('Cartão Pró Vantagens', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8), fontSize: 30),),
AspectRatio(
aspectRatio: 1,
child: Image.network(
'https://static.wixstatic.com/media/d170e1_80b5f6510f5841c19046f1ed5bca71e4~mv2.png/v1/fill/w_745,h_595,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es.webp',
fit: BoxFit.fill,
),
),
Divider(),
Container(
height: 150,
child: Row(
children: [
AspectRatio(
aspectRatio: 1,
child: Image.network(
'https://static.wixstatic.com/media/d170e1_486dd638987b4ef48d12a4bafee20e80~mv2.png/v1/fill/w_684,h_547,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es_2.webp',
fit: BoxFit.fill,
),
),
Padding(
padding: const EdgeInsets.only(left:20.0),
child: RichText(
text: TextSpan(children: <TextSpan>[
TextSpan(
text: 'Adquira já o seu',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
TextSpan(
text: '\n\CARTÃO PRÓ VANTAGENS',
style: TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 30, 158, 8)),
),
]),
),
),
],
),
),
Divider(),
tableBeneficios(),
Divider(),
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Text(
'O cartão Pró-Vantagens é sediado na cidade de Hortolândia/SP e já está no mercado há mais de 3 anos. Somos um time de profissionais apaixonados por gestão de benefícios e empenhados em gerar o máximo de valor para os conveniados.'),
FlatButton(
onPressed: () {
launch(
'https://www.youtube.com/watch?v=VFnDo3JUzjs');
},
child: Text('SAIBA MAIS')),
],
),
),
Container(
color: Color.fromARGB(255, 105, 190, 90),
child: Column(
children: <Widget>[
Row(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'© 2020 todos os direitos reservados a Cartão Pró Vantagens.',
style: TextStyle(fontSize: 10),
),
)
],
),
Divider(),
Row(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Rua Luís Camilo de Camargo, 175 -\n\Centro, Hortolândia (piso superior)',
style: TextStyle(fontSize: 10),
),
),
Padding(
padding: const EdgeInsets.only(left: 16),
child: IconButton(
icon: Icon(CustomIcons.facebook),
color: Colors.black,
onPressed: () {
launch(
'https://www.facebook.com/provantagens/');
},
),
),
Padding(
padding: const EdgeInsets.only(left: 16),
child: IconButton(
icon: Icon(CustomIcons.instagram),
color: Colors.black,
onPressed: () {
launch(
'https://www.instagram.com/cartaoprovantagens/');
},
),
),
],
),
],
),
)
],
),
]);
},
)
),
);
}
tableBeneficios() {
return Table(
defaultColumnWidth: FlexColumnWidth(120.0),
border: TableBorder(
horizontalInside: BorderSide(
color: Colors.black,
style: BorderStyle.solid,
width: 1.0,
),
verticalInside: BorderSide(
color: Colors.black,
style: BorderStyle.solid,
width: 1.0,
),
),
children: [
_criarTituloTable(",Plus, Premium"),
_criarLinhaTable("Seguro de vida\n\(Morte Acidental),X,X"),
_criarLinhaTable("Seguro de Vida\n\(Qualquer natureza),,X"),
_criarLinhaTable("Invalidez Total e Parcial,X,X"),
_criarLinhaTable("Assistência Residencial,X,X"),
_criarLinhaTable("Assistência Funeral,X,X"),
_criarLinhaTable("Assistência Pet,X,X"),
_criarLinhaTable("Assistência Natalidade,X,X"),
_criarLinhaTable("Assistência Eletroassist,X,X"),
_criarLinhaTable("Assistência Alimentação,X,X"),
_criarLinhaTable("Descontos em Parceiros,X,X"),
],
);
}
_criarLinhaTable(String listaNomes) {
return TableRow(
children: listaNomes.split(',').map((name) {
return Container(
alignment: Alignment.center,
child: RichText(
text: TextSpan(children: <TextSpan>[
TextSpan(
text: name != "X" ? '' : 'X',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
TextSpan(
text: name != 'X' ? name : '',
style: TextStyle(
fontSize: 10.0,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 30, 158, 8)),
),
]),
),
padding: EdgeInsets.all(8.0),
);
}).toList(),
);
}
_criarTituloTable(String listaNomes) {
return TableRow(
children: listaNomes.split(',').map((name) {
return Container(
alignment: Alignment.center,
child: RichText(
text: TextSpan(children: <TextSpan>[
TextSpan(
text: name == "" ? '' : 'Plano ',
style: TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
TextSpan(
text: name,
style: TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 30, 158, 8)),
),
]),
),
padding: EdgeInsets.all(8.0),
);
}).toList(),
);
}
void _storePosition(TapDownDetails details) {
_tapPosition = details.globalPosition;
}
}
I forked the library to create a custom carousel for my company's project, and since we updated flutter to 2.x we had the same problem.
To fix this just update boolean expressions like
if(carouselState.pageController.position.minScrollExtent == null ||
carouselState.pageController.position.maxScrollExtent == null){ ... }
to
if(!carouselState.pageController.position.hasContentDimensions){ ... }
Here is flutter's github reference.
This worked for me
So I edited scrollposition.dart package
from line 133
#override
//double get minScrollExtent => _minScrollExtent!;
// double? _minScrollExtent;
double get minScrollExtent {
if (_minScrollExtent == null) {
_minScrollExtent = 0.0;
}
return double.parse(_minScrollExtent.toString());
}
double? _minScrollExtent;
#override
// double get maxScrollExtent => _maxScrollExtent!;
// double? _maxScrollExtent;
double get maxScrollExtent {
if (_maxScrollExtent == null) {
_maxScrollExtent = 0.0;
}
return double.parse(_maxScrollExtent.toString());
}
double? _maxScrollExtent;
Just upgrade to ^3.0.0 Check here https://pub.dev/packages/carousel_slider
I faced the same issue.
This is how I solved it
class PlansPage extends StatefulWidget {
const PlansPage({Key? key}) : super(key: key);
#override
State<PlansPage> createState() => _PlansPageState();
}
class _PlansPageState extends State<PlansPage> {
int _currentPage = 1;
late CarouselController carouselController;
#override
void initState() {
super.initState();
carouselController = CarouselController();
}
}
Then put initialization the carouselController inside the initState method I was able to use the methods jumpToPage(_currentPage ) and animateToPage(_currentPage) etc.
I use animateToPage inside GestureDetector in onTap.
onTap: () {
setState(() {
_currentPage = pageIndex;
});
carouselController.animateToPage(_currentPage);
},
I apologize in advance if this is inappropriate.
I solved the similar problem as follows. You can take advantage of the Boolean variable. I hope, help you.
child: !loading ? HomeCarousel(homeManager) : Center(child:ProgressIndicator()),
or
child: isLoading ? HomeCarousel(homeManager) : SplashScreen(),
class SplashScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Loading...')
),
);
}
}