Related
I want to intigrate stripe payment but i get this error
I am using flutter_stripe: ^8.0.0+1
ERROR MESSAGES
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Instance of 'StripeConfigException'
E/flutter (20428): #0 Stripe.publishableKey (package:flutter_stripe/src/stripe.dart:30:7)
E/flutter (20428): #1 Stripe.applySettings (package:flutter_stripe/src/stripe.dart:104:25)
E/flutter (20428): #2 Stripe._awaitForSettings (package:flutter_stripe/src/stripe.dart:624:25)
E/flutter (20428): #3 Stripe.initPaymentSheet (package:flutter_stripe/src/stripe.dart:463:11)
E/flutter (20428): #4 _stripeState.intpayment (package:ecommerce/payment_intigration/stripe.dart:42:23)
E/flutter (20428):
E/flutter (20428):
I/flutter (20428): Instance of 'StripeConfigException'
CODE
void main() {
WidgetsFlutterBinding.ensureInitialized();
Stripe.publishableKey = 'key';
runApp( MaterialApp(
home: MediaQuery(
data: MediaQueryData(),
child: stripe(),
),
),);
}
class stripe extends StatefulWidget {
const stripe({Key? key}) : super(key: key);
#override
State<stripe> createState() => _stripeState();
}
class _stripeState extends State<stripe> {
Future<void> intpayment(
{required String email, required double amount})async{
try{
final response= await http.post(Uri.parse("https://api.stripe.com/v1/payment_intents")
,body:{
"receipt_email": email,
"amount": amount.toInt().toString(),
"currency": "usd"
},
headers: {
'Authorization': 'Bearer ' + 'secret key',
'Content-Type': 'application/x-www-form-urlencoded'
}
);
final jsonresponse=jsonDecode(response.body);
print(jsonresponse.toString());
Stripe.instance.initPaymentSheet(paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: jsonresponse['paymentIntent'],
merchantDisplayName: 'Grocery Flutter course',
customerId: jsonresponse['customer'],
customerEphemeralKeySecret: jsonresponse['ephemeralKey'],
));
await Stripe.instance.presentPaymentSheet();
print("payment successfull");
}
catch(e){
if (e is StripeException) {
print(e);
}
print(e);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Payment Demo'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
intpayment(email: "zohaib6778#gmail.com", amount: 50.0);
},
child: Text("Pay20\$"),
),
),
);
}
}
`
can any one give me the solving for this error.
i don't know when the error made and don't know what is the part of code that make this problem
this is the error that shown when i run program
═══════ Exception caught by widgets library ═══════════════════════════════════
The following _TypeError was thrown building MyApp(dirty):
type '_Type' is not a subtype of type 'BuildContext'
The relevant error-causing widget was
MyApp
package:my_first_app/main.dart:15
When the exception was thrown, this was the stack
#0 TasksCubit.get
package:my_first_app/…/mycubitclasses/taskscubit_class.dart:14
#1 new HomeLayout
package:my_first_app/layout/homelayout.dart:29
#2 MyApp.build
package:my_first_app/main.dart:24
#3 StatelessElement.build
package:flutter/…/widgets/framework.dart:4876
#4 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4806
#5 Element.rebuild
package:flutter/…/widgets/framework.dart:4529
#6 ComponentElement._firstBuild
package:flutter/…/widgets/framework.dart:4787
#7 ComponentElement.mount
package:flutter/…/widgets/framework.dart:4781
#8 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3817
#9 Element.updateChild
package:flutter/…/widgets/framework.dart:3551
#10 RenderObjectToWidgetElement._rebuild
package:flutter/…/widgets/binding.dart:1202
#11 RenderObjectToWidgetElement.mount
package:flutter/…/widgets/binding.dart:1171
#12 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure>
package:flutter/…/widgets/binding.dart:1119
#13 BuildOwner.buildScope
package:flutter/…/widgets/framework.dart:2597
#14 RenderObjectToWidgetAdapter.attachToRenderTree
package:flutter/…/widgets/binding.dart:1118
#15 WidgetsBinding.attachRootWidget
package:flutter/…/widgets/binding.dart:953
#16 WidgetsBinding.scheduleAttachRootWidget.<anonymous closure>
and this is my main.dart file
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:my_first_app/layout/homelayout.dart';
import 'package:my_first_app/moduls/login/login.dart';
import 'package:my_first_app/moduls/messanger/messangerscreen.dart';
import 'package:my_first_app/moduls/counter/counter_screen.dart';
import 'package:my_first_app/moduls/messanger/mydesign.dart';
import 'moduls/homescreen/HomeScreen.dart';
import 'moduls/counter/counter_screen.dart';
import 'moduls/bmiscreen/ibm_calculator.dart';
import 'shared/bloc_observ.dart';
void main() {
// Bloc.observer = MyBlocObserver();
return runApp(MyApp());
}
//=========================================================
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context)
{
return MaterialApp(
debugShowCheckedModeBanner: false ,
home: HomeLayout(),
);
}
}
i added cubit class ..maybe problem appear when i add it
and this is my HomeLayout screen
// ignore_for_file: prefer_const_constructors
import 'dart:ffi';
import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:my_first_app/moduls/archive_task_screen/archive_task.dart';
import 'package:my_first_app/moduls/done_task_screen/done_task.dart';
import 'package:my_first_app/moduls/new_task_screen/new_task.dart';
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:my_first_app/shared/componants/componants.dart';
import 'package:my_first_app/shared/mycubitclasses/taskscubit_class.dart';
import 'package:my_first_app/shared/mycubitclasses/taskstates.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import '../shared/componants/constants.dart';
class HomeLayout extends StatelessWidget
{
//======================variables===============================
var scaffoldkey = GlobalKey<ScaffoldState>();
var formkey = GlobalKey<FormState>();
var titleController = TextEditingController();
var timeController = TextEditingController();
var dateController = TextEditingController();
TasksCubit cubitt = TasksCubit.get(context);
// scaffold contain in this screen :
// 1. appBar 2. FAB floatingActionButton 3. body 4. bottomNavigationBar
//=================================================================
//=================================================================
#override
Widget build(BuildContext context)
{
return BlocProvider (
create: (context) {
return TasksCubit()..creatDataBase();
},
child: Scaffold(
key: scaffoldkey,
//========================app bar =================================
appBar: AppBar(
title: Text(
cubitt.titls[cubitt.currentindex],
),
),
//===========================body ======================================
body: BlocBuilder<TasksCubit,TasksStates>(
builder: (BuildContext context, TasksStates state)
{
if (state is InsertDataBase)
{
Navigator.pop(context);
}
return cubitt.screens[cubitt.currentindex];
}),
//===========================FAB======================================
floatingActionButton: FloatingActionButton(
onPressed: ()
{
if (cubitt. isBottomSheetShown)
{
cubitt.InserttTODataBase(
titel: titleController.text,
date: dateController.text,
time: timeController.text,
status: 'new',
).then((value) {
print( '*************************** Insert succesfully **************************');
cubitt.ChangeBottomState(false,Icons.edit);
});
}
else // if bottomsheet closed
{
scaffoldkey.currentState!.showBottomSheet(
(context) => Container(
padding: EdgeInsets.all(20.0),
color: Colors.grey[200],
child: Column(
mainAxisSize: MainAxisSize.min,
children:
[
DefoultFormField(
controller: titleController,
label: 'input title',
prefix: Icons.title,
type: TextInputType.text,
validate: ((String value) {}),
// validate: (String? value){
// if(value!.isEmpty)
// {
// return' must title not empty ';
// }
// return null ;
// },
),
SizedBox(
height: 5.0,
),
//////////////////////////////////////////////////////////////////////
DefoultFormField(
controller: timeController,
label: 'input time',
prefix: Icons.watch,
type: TextInputType.datetime,
validate: ((String value) {}),
// validate: (String? value){
// if(value!.isEmpty)
// {
// return' must time not empty ';
// }
// // return null ;
// },
ontap: () {
showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
).then((value) {
return timeController.text =
value!.format(context);
});
},
),
///////////////////////////// formfied date /////////////////////////////////////////
SizedBox(
height: 5.0,
),
DefoultFormField(
controller: dateController,
label: 'input date',
prefix: Icons.calendar_today,
type: TextInputType.datetime,
validate: ((String value) {}),
// validate: (String value){
// if(value.isEmpty)
// return' must date not empty ';
// return null ;
// },
ontap: () {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime.parse('2023-05-05'),
).then((value) {
return dateController.text =
DateFormat.yMMMd().format(value!);
});
},
),
//////////////////////////////////////////////////////////////////////
],
),
),
// if i closed the bottomSheet in my hand not in FAB will give error so i did this :
)
.closed .then((value)
{
cubitt.ChangeBottomState(false,Icons.edit);
}); // closed func
cubitt.ChangeBottomState(true,Icons.add);
}
},
child: Icon(
cubitt. fabicon,
),
),
//======================== BottomNavigationBar =========================================
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
elevation: 50.0,
currentIndex: cubitt.currentindex,
onTap: (index) {
cubitt.ChangeIndex(index);
},
backgroundColor: Colors.blue[200],
items:
[
BottomNavigationBarItem(
icon: Icon(
Icons.menu,
),
label: 'NEW TASK',
),
BottomNavigationBarItem(
icon: Icon(
Icons.done_all,
),
label: 'DONE TASK',
),
BottomNavigationBarItem(
icon: Icon(
Icons.archive,
),
label: 'ARCHIVE TASK',
),
],
),
),
);
}
//============================ finish scaffold =======================================
}
and this is TasksCubit class
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:my_first_app/moduls/new_task_screen/new_task.dart';
import 'package:my_first_app/shared/mycubitclasses/taskstates.dart';
import 'package:sqflite/sqflite.dart';
import '../../moduls/archive_task_screen/archive_task.dart';
import '../../moduls/done_task_screen/done_task.dart';
class TasksCubit extends Cubit<TasksStates>
{
TasksCubit():super ( InitailTasksState());
static TasksCubit get(context)=>BlocProvider.of(context);
//////////////////////////////////////////////////////////////////////
int currentindex = 0;
List<Widget> screens = [
NewTask(),
DoneTask(),
ArchiveTask(),
];
List<String> titls = [
'new task',
'done task ',
'archive task',
];
void ChangeIndex (index)
{
currentindex =index;
emit(changBottomNavBar());
}
var isBottomSheetShown = false;
IconData fabicon = Icons.add;
void ChangeBottomState ( bool isShow ,IconData icon )
{
isBottomSheetShown=isShow;
fabicon=icon;
emit(changBottomSheet());
}
// **************************** DataBase ************************************
late Database Mydatabase;
List<Map> tasks =[];
void creatDataBase() {
openDatabase(
'todo.db',
version: 1,
onCreate: (db, version) {
print(
'************************** daataBase Created ****************************');
db .execute(
'CREATE TABLE tasks (id INTEGER PRIMARY KEY,titel TEXT,date TEXT,time TEXT,status TEXT)')
.then((value) {
print(
'************************** table creaated ****************************');
}).catchError((err) {
print(
'************************** error in create table ****************************${err.toString()}');
});
},
onOpen: (db) {
// ignore: avoid_print
print(
'************************** daataBase opened ****************************');
GetDataFromDataBase(db).then((value)
{
tasks=value;
emit(GetFromDataBase());
print(
'************************** your table next ****************************');
print(tasks);
print(
'************************** your table above ****************************');
}
).catchError((err){
print(
'************************** error when get data ${err.toString()} ****************************');
});
},
).then((value) {
Mydatabase=value;
emit(CreatDataBase());
});
}
//============================================================================================
//========================== insert data to dataBase =========================================
InserttTODataBase(
{
required String titel,
required String date,
required String time,
required String status
}) async
{
await Mydatabase.transaction((txn)
{
return txn.rawInsert('INSERT INTO tasks (titel,date,time,status) VALUES ("$titel","$date","$time","$status")')
.then((value)
{
print('************************** inserted successfulyt to id ${value} ****************************');
emit(InsertDataBase());
GetDataFromDataBase(Mydatabase).then((value)
{
tasks=value;
emit(GetFromDataBase());
print( '************************** your table next ****************************');
print(tasks);
print('************************** your table above ****************************');
});
}).catchError((err)
{
print('************************** error when inserted to record ****************************${err.toString()}');
});
});
}
/////////////////////////// get data from dataBase////////////////////////////////////
//============================================================================================
Future<List<Map>> GetDataFromDataBase (database) async
{
return await database.rawQuery('SELECT * FROM tasks');
}
}
Context isn't available where you call:
TasksCubit cubitt = TasksCubit.get(context).
Maybe not a good idea, but if you run that line inside the build method, it'll work.
i have issue when i tried to implement saving data by local storage,
i can't to ask for the long text so i'll describe issue now & ask question:
issue :
radixString
question:
i forgot step for saving with local storage?
how to resolve radixString? i've to follow step with any stack overflow answer, with int.parse(restaurant.id).toRadixString(16)
okey, i will to show my code base at below :
CLEAN ARCHITECTURE BASE:
File on Data folder:
data: database_helper.dart
import 'package:makanyuk/data/model/resto_table.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:core';
class DatabaseHelper {
static Database? _database;
Future<Database?> get database async {
if (_database == null) {
_database = await _initDb();
}
return _database;
}
static const String _tblFavlist = 'favlist';
Future<Database> _initDb() async {
final path = await getDatabasesPath();
final databasePath = '$path/resto.db';
var db = await openDatabase(databasePath, version: 1, onCreate: _onCreate);
return db;
}
void _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $_tblFavlist (
id TEXT PRIMARY KEY,
name TEXT,
description TEXT,
pictureId TEXT,
city TEXT,
rating TEXT,
);
''');
}
Future<Map<String, dynamic>?> getMovieById(String id) async {
final db = await database;
final results = await db!.query(
_tblFavlist,
where: 'id = ?',
whereArgs: [id],
);
if (results.isNotEmpty) {
return results.first;
} else {
return null;
}
}
Future<int> insert(RestoTable resto) async {
final db = await database;
final result = await db!.insert(_tblFavlist, resto.toJson());
return result;
}
Future<List<Map<String, dynamic>>> getNotes() async {
final db = await _database;
final List<Map<String, dynamic>> results = await db!.query(_tblFavlist);
return results;
}
}
datasource: resto_local_datasource.dart
import 'package:makanyuk/core/exception.dart';
import 'package:makanyuk/data/model/resto_table.dart';
import 'db/database_helper.dart';
abstract class RestoLocalDataSource {
Future<String> insertFavList(RestoTable resto);
Future<List<RestoTable>> getFavList();
Future<RestoTable?> getRestoById(String id);
}
class RestoLocalDataSourceImpl implements RestoLocalDataSource {
final DatabaseHelper db;
RestoLocalDataSourceImpl({required this.db});
#override
Future<String> insertFavList(RestoTable resto) async {
try {
final id = await db.insert(resto);
return 'Added to Favlist';
} catch (e) {
throw DatabaseException(e.toString());
}
}
#override
Future<List<RestoTable>> getFavList() async {
final result = await db.getNotes();
return result.map((e) => RestoTable.fromMap(e)).toList();
}
#override
Future<RestoTable?> getRestoById(String id) async {
final result = await db.getMovieById(id);
if (result != null) {
return RestoTable.fromMap(result);
} else {
return null;
}
}
}
repositories: resto_repositories.dart
import 'dart:io';
import 'package:dartz/dartz.dart';
import 'package:makanyuk/data/datasources/resto_remote_data_source.dart';
import 'package:makanyuk/data/model/resto_table.dart';
import 'package:makanyuk/domain/entities/restaurant.dart';
import 'package:makanyuk/domain/entities/restaurant_detail.dart';
import '../../core/exception.dart';
import '../../core/failure.dart';
import '../../domain/repositories/resto_repository.dart';
import '../datasources/resto_local_data_source.dart';
class RestoRepositoryImpl implements RestoRepository {
final RestoRemoteDataSource remoteDataSource;
final RestoLocalDataSource localDataSource;
RestoRepositoryImpl(
{required this.remoteDataSource, required this.localDataSource});
#override
Future<Either<Failure, List<Restaurant>>> getAllResto() async {
try {
final result = await remoteDataSource.getAllResto();
return Right(result.map((e) => e.toEntity()).toList());
} on ServerException {
return Left(ServerFailure(''));
} on SocketException {
return Left(ConnectionFailure('Failed to connectiion'));
}
}
#override
Future<Either<Failure, RestaurantDetail>> getDetailResto(id) async {
try {
final result = await remoteDataSource.getDetailResto(id);
return Right(result.toEntity());
} on ServerException {
return Left(ServerFailure(''));
} on SocketException {
return Left(ConnectionFailure('Failed to connectiion'));
}
}
#override
Future<Either<Failure, List<Restaurant>>> searchResto(query) async {
try {
final result = await remoteDataSource.searchResto(query);
return Right(result.map((e) => e.toEntity()).toList());
} on ServerException {
return Left(ServerFailure(''));
} on SocketException {
return Left(ConnectionFailure('Failed to connectiion'));
}
}
#override
Future<Either<Failure, List<Restaurant>>> getFavList() async {
final result = await localDataSource.getFavList();
return Right(result.map((e) => e.toEntity()).toList());
}
#override
Future<Either<Failure, String>> saveFavList(RestaurantDetail resto) async {
try {
final result =
await localDataSource.insertFavList(RestoTable.fromEntity(resto));
return Right(result);
} on DatabaseException catch (e) {
return Left(DatabaseFailure(e.message));
} catch (e) {
throw e;
}
}
#override
Future<bool> isAddedToFavlist(String id) async {
final result = await localDataSource.getRestoById(id);
return result != null;
}
}
File on Domain folder:
repositories: resto_repositories.dart
import 'package:dartz/dartz.dart';
import 'package:makanyuk/domain/entities/restaurant.dart';
import 'package:makanyuk/domain/entities/restaurant_detail.dart';
import '../../core/failure.dart';
abstract class RestoRepository {
Future<Either<Failure, List<Restaurant>>> getAllResto();
Future<Either<Failure, RestaurantDetail>> getDetailResto(id);
Future<Either<Failure, List<Restaurant>>> searchResto(query);
Future<Either<Failure, String>> saveFavList(RestaurantDetail resto);
Future<Either<Failure, List<Restaurant>>> getFavList();
Future<bool> isAddedToFavlist(String id);
}
usecase: i have some usecase but it's similary same so i just show 1 example, save_favlist_resto.dart
import 'package:dartz/dartz.dart';
import 'package:makanyuk/domain/entities/restaurant_detail.dart';
import 'package:makanyuk/domain/repositories/resto_repository.dart';
import '../../core/failure.dart';
class SaveFavlistResto {
final RestoRepository repository;
SaveFavlistResto({required this.repository});
Future<Either<Failure, String>> execute(RestaurantDetail resto) {
return repository.saveFavList(resto);
}
}
provider: resto_detail_notifier.dart
import 'package:flutter/material.dart';
import 'package:makanyuk/data/datasources/db/database_helper.dart';
import 'package:makanyuk/domain/usecases/get_detail_resto.dart';
import 'package:makanyuk/domain/usecases/get_favlist_status.dart';
import 'package:makanyuk/domain/usecases/save_favlist_resto.dart';
import '../../core/state_enum.dart';
import '../../domain/entities/restaurant.dart';
import '../../domain/entities/restaurant_detail.dart';
class RestoDetailNotifier extends ChangeNotifier {
static const favlistAddSuccessMessage = 'Added to Favlist';
final GetDetailResto detailResto;
final SaveFavlistResto saveFavlistResto;
final GetfavListStatus getFavListStatus;
DatabaseHelper databaseHelper;
RestoDetailNotifier(
{required this.getFavListStatus,
required this.detailResto,
required this.saveFavlistResto,
required this.databaseHelper}) {
this.databaseHelper = DatabaseHelper();
}
RequestState _restoState = RequestState.Empty;
get restoState => _restoState;
String _message = '';
String get message => _message;
List<Restaurant>? _restaurant;
List<Restaurant>? get restaurant => _restaurant;
RestaurantDetail? _restoDetail;
get restoDetail => _restoDetail;
String _favlistmessage = '';
String get favlistmessage => _favlistmessage;
bool _isAddedtoFavlist = false;
bool get isAddedToFavlist => _isAddedtoFavlist;
Future<void> fetchDetailResto(String id) async {
_restoState = RequestState.Loading;
notifyListeners();
final detailResult = await detailResto.execute(id);
detailResult.fold((failure) {
_restoState = RequestState.Error;
_message = failure.message;
notifyListeners();
}, (resto) {
_restoDetail = resto;
_restoState = RequestState.Loaded;
notifyListeners();
});
}
Future<void> addFavlist(RestaurantDetail resto) async {
final result = await saveFavlistResto.execute(resto);
await result.fold((failure) async {
print('Kalo gagal');
_favlistmessage = failure.message;
}, (successMessafe) async {
print('kesini kalo sukses');
// _favlistmessage = successMessafe;
});
await loadWatchlistStatus(resto.id);
}
Future<void> loadWatchlistStatus(String id) async {
final result = await getFavListStatus.execute(id);
_isAddedtoFavlist = result;
notifyListeners();
}
}
ui/presentation: detail_page.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:makanyuk/domain/entities/restaurant_detail.dart';
import 'package:makanyuk/presentation/provider/resto_detail_notifier.dart';
import 'package:makanyuk/presentation/widget/rating_item.dart';
import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../core/constants.dart';
import '../../core/state_enum.dart';
class DetailPage extends StatefulWidget {
static const ROUTE_NAME = '/detail';
String id;
DetailPage({Key? key, required this.id}) : super(key: key);
#override
State<DetailPage> createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
#override
void initState() {
// TODO: implement initState
super.initState();
Future.microtask(() =>
Provider.of<RestoDetailNotifier>(context, listen: false)
..fetchDetailResto(widget.id));
}
#override
Widget build(BuildContext context) {
return Scaffold(
// floatingActionButton: FloatingActionButton(
// backgroundColor: Colors.red,
// onPressed: () {
// final result =
// Provider.of<RestoDetailNotifier>(context, listen: false)
// .addFavlist(
// Provider.of<RestoDetailNotifier>(context, listen: false)
// .restoDetail
// .id);
// },
// child: Icon(CupertinoIcons.heart_circle),
// ),
body: Consumer<RestoDetailNotifier>(builder: ((context, value, child) {
final state = value.restoState;
if (state == RequestState.Loading) {
return Center(child: CupertinoActivityIndicator());
} else if (state == RequestState.Loaded) {
return DetailResto(restaurantDetail: value.restoDetail);
} else {
return Text(value.message);
}
})));
}
}
class DetailResto extends StatelessWidget {
DetailResto({required this.restaurantDetail});
final RestaurantDetail restaurantDetail;
#override
Widget build(BuildContext context) {
return Scaffold(
body: NestedScrollView(
headerSliverBuilder: ((context, innerBoxIsScrolled) {
return [
SliverAppBar(
actions: [
FloatingActionButton(
backgroundColor: Colors.red,
onPressed: () {
// final detailResult = RestaurantDetail(
// categories: restaurantDetail.categories,
// customerReviews: restaurantDetail.customerReviews,
// id: restaurantDetail.id.toString(),
// name: restaurantDetail.name,
// description: restaurantDetail.description,
// city: restaurantDetail.city,
// address: restaurantDetail.address,
// menus: restaurantDetail.menus,
// pictureId: restaurantDetail.pictureId,
// rating: restaurantDetail.rating);
final result =
Provider.of<RestoDetailNotifier>(context, listen: false)
.addFavlist(restaurantDetail);
},
child: Icon(CupertinoIcons.heart_circle),
),
],
//kalau ingin menyisakan appbar tambahkan pinned : true
leading: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: CircleAvatar(
radius: 15,
backgroundColor: CupertinoColors.white,
child: Icon(
CupertinoIcons.back,
color: Theme.of(context).primaryColorLight,
),
),
),
backgroundColor: CupertinoColors.white,
pinned: true,
expandedHeight: 250,
flexibleSpace: FlexibleSpaceBar(
background: Container(
child: CachedNetworkImage(
fadeInCurve: Curves.slowMiddle,
fit: BoxFit.cover,
imageUrl: '${BASE_URL_LARGE + restaurantDetail.pictureId}',
placeholder: (context, url) => Center(
child: CupertinoActivityIndicator(),
),
errorWidget: (context, url, error) => Icon(Icons.error),
),
),
// centerTitle: true,
// title: Container(
// padding: EdgeInsets.all(8),
// decoration: BoxDecoration(
// color: CupertinoColors.systemPurple,
// borderRadius: BorderRadius.circular(16)),
// child: Text(
// restaurantDetail.name,
// style: Theme.of(context)
// .textTheme
// .titleMedium!
// .copyWith(color: Theme.of(context).primaryColorLight),
// ),
// ),
titlePadding: const EdgeInsets.only(left: 16, bottom: 16),
),
)
];
}),
body: SingleChildScrollView(
reverse: false,
child:
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(children: [
Icon(
Icons.place,
size: 14,
),
SizedBox(
width: 5,
),
Text(restaurantDetail.city,
style: Theme.of(context).textTheme.headlineSmall),
Spacer(),
Row(
children: [1, 2, 3, 4, 5]
.map((e) => RatingItem(
index: e.toInt(), rating: restaurantDetail.rating))
.toList(),
)
]),
),
Padding(
padding: const EdgeInsets.all(16),
child: Text(
restaurantDetail.description,
maxLines: 10,
style: Theme.of(context).textTheme.subtitle1,
),
),
CupertinoButton(
child: Column(
// mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Menu\'s',
style: Theme.of(context).textTheme.bodySmall,
),
Row(
children: [
Text(
'click to show',
style: Theme.of(context).textTheme.bodyText2,
),
Icon(Icons.logo_dev)
],
),
],
),
onPressed: () {
showModalBottomSheet(
context: context,
builder: (context) {
return ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Drink',
style: Theme.of(context).textTheme.bodyText1,
),
),
...restaurantDetail.menus.drinks
.map((e) => Padding(
padding: const EdgeInsets.only(
top: 5, left: 16),
child: Text(e.name),
))
.toList(),
const SizedBox(
height: 16,
),
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Food',
style: Theme.of(context).textTheme.bodyText1,
),
),
...restaurantDetail.menus.foods
.map((e) => Padding(
padding: const EdgeInsets.only(
top: 5, left: 16),
child: Text(e.name),
))
.toList()
],
);
});
}),
Padding(
padding: const EdgeInsets.only(left: 16),
child: Text(
'Review\'s',
style: Theme.of(context).textTheme.labelLarge,
),
),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
...restaurantDetail.customerReviews
.map((e) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Padding(
padding:
const EdgeInsets.only(bottom: 10),
child: Text(
e.name,
style: Theme.of(context)
.textTheme
.labelMedium,
),
),
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
// mainAxisAlignment:
// MainAxisAlignment.spaceEvenly,
children: [
Text(
e.review,
style: Theme.of(context)
.textTheme
.subtitle2!
.copyWith(
color: Colors.black54),
),
const SizedBox(
height: 5,
),
Text(
e.date,
style: Theme.of(context)
.textTheme
.labelSmall!
.copyWith(color: Colors.grey),
),
],
),
],
),
)),
))
.toList()
],
),
),
])),
));
}
}
issue's:
E/flutter ( 5086): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FormatException: Invalid radix-10 number (at character 1)
E/flutter ( 5086): rqdv5juczeskfw1e867
E/flutter ( 5086): ^
E/flutter ( 5086):
E/flutter ( 5086): #0 RestoRepositoryImpl.saveFavList
package:makanyuk/…/repositories/resto_repositories_impl.dart:72
E/flutter ( 5086): #1 SaveFavlistResto.execute
package:makanyuk/…/usecases/save_favlist_resto.dart:11
E/flutter ( 5086): #2 RestoDetailNotifier.addFavlist
package:makanyuk/…/provider/resto_detail_notifier.dart:61
E/flutter ( 5086): #3 DetailResto.build.<anonymous closure>.<anonymous closure>
package:makanyuk/…/page/detail_page.dart:89
E/flutter ( 5086): #4 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:1005
E/flutter ( 5086): #5 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:198
E/flutter ( 5086): #6 TapGestureRecognizer.handleTapUp
package:flutter/…/gestures/tap.dart:613
E/flutter ( 5086): #7 BaseTapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:298
E/flutter ( 5086): #8 BaseTapGestureRecognizer.acceptGesture
package:flutter/…/gestures/tap.dart:269
E/flutter ( 5086): #9 GestureArenaManager.sweep
package:flutter/…/gestures/arena.dart:157
E/flutter ( 5086): #10 GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:449
E/flutter ( 5086): #11 GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:425
E/flutter ( 5086): #12 RendererBinding.dispatchEvent
package:flutter/…/rendering/binding.dart:329
E/flutter ( 5086): #13 GestureBinding._handlePointerEventImmediately
package:flutter/…/gestures/binding.dart:380
E/flutter ( 5086): #14 GestureBinding.handlePointerEvent
package:flutter/…/gestures/binding.dart:344
E/flutter ( 5086): #15 GestureBinding._flushPointerEventQueue
package:flutter/…/gestures/binding.dart:302
E/flutter ( 5086): #16 GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:285
E/flutter ( 5086): #17 _rootRunUnary (dart:async/zone.dart:1442:13)
E/flutter ( 5086): #18 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 5086): #19 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter ( 5086): #20 _invoke1 (dart:ui/hooks.dart:170:10)
E/flutter ( 5086): #21 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
E/flutter ( 5086): #22 _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
E/flutter ( 5086):
I added multiple blocs in my main file and use 1 bloc for every single screen, but when i go to next screen and come back to previous screen then again try to trigger event it gives error of bad state of second bloc.
main class
void main() {
runApp(MultiBlocProvider(
providers:[
BlocProvider<LoginBloc>(
create:(_) => LoginBloc(),
),
BlocProvider<HomeBloc>(
create: (_) => HomeBloc()
),
BlocProvider<UnitBloc>(
create: (_) => UnitBloc()
),
],
child: MyApp()
));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Watchman',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: MyColors.primaryTheme,
bottomSheetTheme: BottomSheetThemeData(backgroundColor: Colors.transparent)
// scaffoldBackgroundColor: MyColors.colorBGBrown
),
home: LoginPage(),
);
}
}
login screen
class LoginPage extends StatefulWidget {
LoginPage({Key? key}) : super(key: key);
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final userController = TextEditingController();
final pswdController = TextEditingController();
String userName = '';
String password = '';
#override
void dispose() {
// TODO: implement dispose
userController.dispose();
pswdController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => LoginBloc(),
child: BlocListener<LoginBloc, LoginState>(
listener: (context, state) {
if (state is LoginSuccessState) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);
} else if (state is LoginErrorState) {
showInSnackBar(context, state.error);
}
},
child: Scaffold(
appBar: AppBar(
title: Text('Login'),
),
body: BlocBuilder<LoginBloc, LoginState>(
builder: (context, state) {
if (state is LoginLoadingState) {
return const Center(
child: CircularProgressIndicator()
);
} else {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Image.asset(
'Assets/iclogo.png',
),
SizedBox(height: 40),
Container(
padding: EdgeInsets.symmetric(
vertical: 5, horizontal: 10),
child: TextFormFieldWidget(
labelText: 'UserName',
controller: userController,
),
),
Container(
padding: EdgeInsets.symmetric(
vertical: 5, horizontal: 10),
child: TextFormFieldWidget(
labelText: 'Password',
isPassword: true,
controller: pswdController,
),
),
Container(
width: double.infinity,
padding: EdgeInsets.symmetric(
vertical: 5, horizontal: 10),
child: ElevatedButtonWidget(
onPressed: () {
userName = userController.text;
password = pswdController.text;
context.read<LoginBloc>().add(
LoginEventSubmit(
username: userName,
password: password)
);
},
text: 'Login',
bgColor: MyColors.colorPrimary,
textColor: Colors.white,
),
),
],
);
}
},
),
),
),
);
}
void showInSnackBar(BuildContext context, String value) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(value),
// duration: Duration(seconds: 2),
),
);
}
}
login_bloc
class LoginBloc extends Bloc<LoginEvent, LoginState> {
LoginBloc() : super(LoginInitial()) {
on<LoginEvent>((event, emit) async {
// TODO: implement event handler
if(event is LoginEventSubmit){
if(event.username.isEmpty || event.password.isEmpty){
emit(LoginErrorState("Please Enter all Fields"));
}else{
emit(LoginLoadingState());
try{
print(event.username +".."+ event.password);
final LoginModel user = await login(event.username ,event.password);
if(user.result=="200"){
emit(LoginSuccessState(user));
}else {
emit(LoginErrorState("UserName or Password is wrong"));
}
}catch (e){
print("error..."+e.toString());
emit(LoginErrorState("Login Failed"));
}
}
}
});
}
Future<LoginModel> login(String username, String pwd) async {
final Dio _dio = Dio();
final queryParameters = {
'username': username,
'pswd':pwd,
};
final response = await _dio.post(AppConstants.login,queryParameters: queryParameters);
final jsonResponse =response.data;
print(jsonResponse.toString());
return LoginModel.fromJson(jsonResponse);
}
}
home screen
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
// Initial Selected Value
#override
void initState() {
// TODO: implement initState
super.initState();
}
Development _selected = Development(
dEVNAME: "Select Building",
dEVCODE: "0"
);
// List of items in our dropdown menu
List<Development>? devList ;
#override
Widget build(BuildContext context) {
return BlocProvider<HomeBloc>(
create: (context) => BlocProvider.of<HomeBloc>(context)..add(GetDevEvent()),
child: BlocListener<HomeBloc, HomeState>(
listener: (context, state) {
// TODO: implement listener
if(state is HomeInitial){
}else if (state is HomeErrorState){
showInSnackBar(context, state.error);
}else if(state is HomeLoadedState){
// devList?.addAll(state.devList);
devList= state.devList;
devList?.add(_selected);
}else if(state is HomeSelectedState){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => UnitsPage(
devCode: state.devCode,
devName: state.devName,
)
)
);
}
},
child: Scaffold(
appBar: AppBar(
title: const Text("Home"),
),
body: BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) {
if (state is HomeLoadingState) {
return const Center(
child: CircularProgressIndicator()
);
} else {
return Center(
child: Padding(
padding:
const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
border: Border.all(color: MyColors.colorBlack),
borderRadius: BorderRadius.circular(15),
),
child: DropdownButton<Development>(
// Initial Value
value: _selected,
isExpanded: true,
// Down Arrow Icon
icon: const Icon(Icons.keyboard_arrow_down),
iconSize: 25,
// Array list of items
items: devList?.map<DropdownMenuItem<Development>>((Development value) {
return DropdownMenuItem<Development>(
value: value,
child: Text(value.dEVNAME!),
);
}).toList(),
// After selecting the desired option,it will
// change button value to selected value
onChanged: (newVal) => setState(() => _selected = newVal!),
)
),
SizedBox(
height: 20,
),
Container(
width: double.infinity,
padding:
EdgeInsets.symmetric(horizontal: 20, vertical: 10),
child: ElevatedButtonWidget(
onPressed: () {
if(_selected.dEVCODE!="0"){
BlocProvider.of<HomeBloc>(context).add(
DevSelectEvent(
devCode:_selected.dEVCODE,
devName: _selected.dEVNAME,
)
);
}else{
String msg = "please "+_selected.dEVNAME!;
showInSnackBar(context, msg);
}
},
text: 'Search',
),
)
],
),
),
);
}
},
),
),
),
);
}
void showInSnackBar(BuildContext context, String value) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(value),
// duration: Duration(seconds: 2),
),
);
}
}
home bloc
class HomeBloc extends Bloc<HomeEvent, HomeState> {
HomeBloc() : super(HomeInitial()) {
on<HomeEvent>((event, emit) async {
// TODO: implement event handler
if(event is GetDevEvent){
emit(HomeLoadingState());
try{
DevData devList = await getData();
if(devList.result =="1"){
emit(HomeLoadedState(devList.development));
print("data.."+ devList.toString());
}else{
emit(HomeErrorState("No data Found"));
}
}catch (e){
print("error..."+e.toString());
emit(HomeErrorState("Failed"));
}
}
if(event is DevSelectEvent){
emit(HomeLoadingState());
emit(HomeSelectedState(event.devName!,event.devCode!));
}
});
}
Future<DevData> getData() async {
final Dio _dio = Dio();
final response = await _dio.post(AppConstants.getDevs);
final jsonResponse =response.data;
print(jsonResponse.toString());
return DevData.fromJson(jsonResponse);
}
}
Error log:
Bad state: Tried to read a provider that threw during the creation of its value.
The exception occurred during the creation of type HomeBloc.
══╡ EXCEPTION CAUGHT BY PROVIDER ╞═══════════════════════════════
The following StateError was thrown:
Bad state: Cannot add new events after calling close
When the exception was thrown, this was the stack:
#1 Bloc.add (package:bloc/src/bloc.dart:84:24)
#2 _HomePageState.build.<anonymous closure> (package:watchman/Home/HomePage.dart:39:64)
#3 _CreateInheritedProviderState.value (package:provider/src/inherited_provider.dart:729:36)
#4 _InheritedProviderScopeElement.value (package:provider/src/inherited_provider.dart:583:33)
#5 Provider.of (package:provider/src/provider.dart:303:37)
#6 ReadContext.read (package:provider/src/provider.dart:656:21)
#7 _BlocListenerBaseState.initState (package:flutter_bloc/src/bloc_listener.dart:147:36)
#8 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4942:57)
#9 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4781:5)
#10 SingleChildWidgetElementMixin.mount (package:nested/nested.dart:222:11)
#11 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3817:16)
#12 Element.updateChild (package:flutter/src/widgets/framework.dart:3551:18)
#13 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4832:16)
#14 _InheritedProviderScopeElement.performRebuild (package:provider/src/inherited_provider.dart:495:11)
#15 Element.rebuild (package:flutter/src/widgets/framework.dart:4529:5)
#16 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4787:5)
#17 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4781:5)
#18 _InheritedProviderScopeElement.mount (package:provider/src/inherited_provider.dart:395:11)
... Normal element mounting (7 frames)
#25 SingleChildWidgetElementMixin.mount (package:nested/nested.dart:222:11)
... Normal element mounting (7 frames)
#32 SingleChildWidgetElementMixin.mount (package:nested/nested.dart:222:11)
... Normal element mounting (283 frames)
#315 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3817:16)
#316 MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6350:36)
#317 Element.updateChild (package:flutter/src/widgets/framework.dart:3551:18)
#318 RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5883:32)
#319 MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6375:17)
#320 Element.updateChild (package:flutter/src/widgets/framework.dart:3530:15)
#321 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4832:16)
#322 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4977:11)
I solve this issue by adding my first event inside initstate(), instead of BlocProvder.
late HomeBloc bloc;
// Initial Selected Value
#override
void initState() {
// TODO: implement initState
bloc = HomeBloc();
bloc.add(GetDevEvent());
super.initState();
}
#override
void dispose() {
// TODO: implement dispose
bloc.close();
super.dispose();
}
I am getting this error when trying to select a different value in DropDownButton. But not able to find the error.
Setting up the BLoC pattern is even easier with the dependency injection features of the Provider package and Streams from RXDart. Shared Preferences makes it possible to store and restore data to and from the bloc when state is lost.
In this video we'll demonstrate the usefulness of all three packages by creating a dynamic theme through BLoC that is seamlessly saved to and restored from the device on startup.
I have followed this example https://www.youtube.com/watch?v=ZpLQIFUqaGI
Main Class
void main() => runApp(Start ());
class Start extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
final String appTitle = "Opn same";
pageTitle(appTitle);
return ChangeNotifierProvider(
create: (BuildContext context) => PreferenceProvider(),
child: Consumer<PreferenceProvider>(
builder: (context, provider, child) {
return StreamBuilder<ThemeModel>(
stream: provider.bloc.customTheme,
builder: (context, snapshotCustomTheme) {
if (!snapshotCustomTheme.hasData) return Container();
return MaterialApp(
theme: snapshotCustomTheme.data!.customTheme,
title: appTitle,
initialRoute: "/Setting",
routes: routes,
);
});
},
),
);
}
}
Setting class:
class Setting extends StatefulWidget {
final String title;
Settings(this.title);
#override
_SettingsState createState() => _SettingsState();
}
class _SettingsState extends State<Settings> {
#override
Widget build(BuildContext context) {
final bloc = Provider.of<Preference>(context).bloc;
return Scaffold(
appBar: AppBar(
title: Text("Settings"),
leading: GestureDetector(
child: Icon(CupertinoIcons.back),
onTap: () {
bloc.savePreferences();
Navigator.of(context).pop();
},
)),
body: Center(
child: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Theme"),
StreamBuilder<ThemeModel>(
stream: bloc.customTheme,
builder: (context, snapshot) {
if (!snapshot.hasData) return Container();
return Container(
padding: EdgeInsets.all(20),
child: DropdownButton(
value: snapshot.data!.value,
items: [
DropdownMenuItem(
child: Text("Default"),
value: 1,
),
DropdownMenuItem(
child: Text("Drala"),
value: 2,
),
DropdownMenuItem(
child: Text("gold"),
value: 3,
)
],
onChanged: (int? value) {
print("value = $value");
setState(() {
bloc.changeTheme(bloc.inToTheme(value!)); **// Getting error here**
});
},
),
);
})
],
),
),
],
),
),
);
}
}
ThemeModel Class
class ThemeModel{
final ThemeData customTheme;
final int value;
ThemeModel ({ required this.customTheme, required this.value,});
}
preference bloc:
class PreferenceBloc {
final _customTheme = BehaviorSubject<ThemeModel>();
//Getters
Stream<Theodel> get customTheme => _customTheme.stream;
//Setters
Function(ThemeModel) get chanheme => _customTheme.sink.add;
indexToTheme(int value) {
return _customTheme.firstWhere((x) => x.value==value);
}
savePreferences() async {
SharedPreferences prefs = await Shareferences.getInstance();
await prefs.setInt('themeValue', _customTheme.value.value);
}
loadPreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int? themeValue = prefs.getInt('themeValue');
if (themeValue != null){
changeTheme(indeheme(themeValue));
} else {
changeTheme(ThemeModel(customTheme: ThemeData(
primaryColor: Color.fromRGBO(58, 66, 86, 1.0),
scaffoldBackgroundColor: Color.fromRGBO(247, 247, 247, 1.0),
brightness: Brightness.light,
visualDensity: VisualDensity(vertical: 0.5, horizontal: 0.5),
primaryColorBrightness: Brightness.light,
primaryTextTheme: TextTheme(
headline6: TextStyle(
fontWeight: FontWeight.w600,
fontFamily: "Raleway",
fontStyle: FontStyle.normal,
fontSize: 22.0,
letterSpacing: 1.6,
wordSpacing: 1.6,
color: Colors.white70,
),
),
),value: 2, ));
}
}
dispose() {
_customTheme.close();
}
}
class PreferenceProvider with ChangeNotifier {
late ThemePreferenceBloc _bloc;
ThemePreferenceProvider() {
_bloc = ThemePreferenceBloc();
_bloc.loadPreferences();
}
ThemeBloc get bloc => _bloc;
}
Error I am getting:
Performing hot restart...
Syncing files to device Android SDK built for x86...
Restarted application in 1,900ms.
I/zygote ( 6068): Do full code cache collection, code=120KB, data=83KB
I/zygote ( 6068): After code cache collection, code=111KB, data=66KB
I/flutter ( 6068): value = 3
E/flutter ( 6068): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type 'Future<ThemeModel>' is not a subtype of type 'ThemeModel'
E/flutter ( 6068): #0 _SettingsState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:open_sesame/view/settings/settings.dart:65:55)
E/flutter ( 6068): #1 State.setState (package:flutter/src/widgets/framework.dart:1088:30)
E/flutter ( 6068): #2 _SettingsState.build.<anonymous closure>.<anonymous closure> (package:open_sesame/view/settings/settings.dart:64:31)
E/flutter ( 6068): #3 _DropdownButtonState._handleTap.<anonymous closure> (package:flutter/src/material/dropdown.dart:1266:25)
E/flutter ( 6068): #4 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter ( 6068): #5 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter ( 6068): <asynchronous suspension>
E/flutter ( 6068):
Please help.. Thanks in advance..
If i have to guess you're missing an await where you're calling the function of type Future<ThemeModel>
Maybe share a full example if you want to debug it here further.
The reason I was not able to get it working was I was not able to access the data stored in another file. So now I brought the data into the same file.
import 'package:flutter/material.dart';
import 'package:rxdart/subjects.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:testing/models/color.dart';
class PreferenceBloc{
final _brightness = BehaviorSubject<Brightness>();
final _primaryColor = BehaviorSubject<ColorModel>();
final _colors = [
ColorModel(color: Colors.blue,index: 0.0, name: 'Blue'),
ColorModel(color: Colors.green,index: 1.0, name: 'Green'),
ColorModel(color: Colors.red,index: 2.0, name: 'Red'),
ColorModel(color: Colors.white,index: 3.0, name: 'White'),
];
//Getters
Stream<Brightness> get brightness => _brightness.stream;
Stream<ColorModel> get primaryColor => _primaryColor.stream;
//Setters
Function(Brightness) get changeBrightness => _brightness.sink.add;
Function(ColorModel) get changePrimaryColor => _primaryColor.sink.add;
indexToPrimaryColor(double index){
return _colors.firstWhere((x) => x.index==index);
}
savePreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if (_brightness.value == Brightness.light){
await prefs.setBool('dark', false);
} else {
await prefs.setBool('dark', true);
}
await prefs.setDouble('colorIndex', _primaryColor.value.index);
}
loadPreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool? darkMode=prefs.getBool('dark');
double? colorIndex = prefs.getDouble('colorIndex');
if (darkMode != null){
(darkMode == false) ? changeBrightness(Brightness.light) : changeBrightness(Brightness.dark);
} else {
changeBrightness(Brightness.light);
}
if (colorIndex != null){
changePrimaryColor(indexToPrimaryColor(colorIndex));
} else {
changePrimaryColor(ColorModel(color: Colors.blue,index: 0.0, name: 'Blue'));
}
}
dispose(){
_primaryColor.close();
_brightness.close();
}
}