import 'package:calendar_app/consts/routes.dart';
import 'package:calendar_app/controller/task_controller.dart';
import 'package:calendar_app/models/task.dart';
import 'package:calendar_app/services/notification_service.dart';
import 'package:calendar_app/widgets/button.dart';
import 'package:calendar_app/widgets/task_tile.dart';
import 'package:date_picker_timeline/date_picker_timeline.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:intl/intl.dart';
import 'dart:developer' as devtools show log;
import 'package:get/get.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
DateTime _selectDate = DateTime.now();
final _taskController = Get.put(TaskController());
var notif;
#override
void initState() {
super.initState();
notif = Notif();
notif.initializeNotification();
notif.requestIOSPermissions();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromARGB(255, 202, 202, 202),
body: Column(
children: [
Container(
margin: const EdgeInsets.fromLTRB(20, 50, 20, 0),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
// Date
DateFormat.yMMMMd().format(DateTime.now()),
style: const TextStyle(
fontSize: 20,
),
),
const SizedBox(
height: 10,
),
const Text(
// Today
'Today',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
],
),
MyButton(
// Add Task
label: '+ Add Task',
onPressed: () async {
await Navigator.of(context).pushNamed(
addTaskRoute,
// (route) => false,
);
},
),
],
),
const SizedBox(
height: 20,
),
DatePicker(
// Calendar
DateTime.now(),
height: 100,
width: 80,
initialSelectedDate: DateTime.now(),
selectionColor: const Color.fromARGB(255, 12, 103, 179),
selectedTextColor: Colors.white,
dateTextStyle: const TextStyle(
fontSize: 35,
color: Colors.grey,
),
dayTextStyle: const TextStyle(
fontSize: 15,
color: Colors.grey,
),
monthTextStyle: const TextStyle(
fontSize: 15,
color: Colors.grey,
),
onDateChange: (date) {},
),
const SizedBox(
height: 20,
),
],
),
),
_showTasks(),
],
),
);
}
_showTasks() {
return Expanded(
child: Obx(
() {
return ListView.builder(
itemCount: _taskController.taskList.length,
itemBuilder: (_, index) {
devtools.log(_taskController.taskList.length.toString());
return AnimationConfiguration.staggeredList(
position: index,
child: SlideAnimation(
child: FadeInAnimation(
child: Row(
children: [
GestureDetector(
onTap: () {
devtools.log('tapped');
_showBottomSheet(
context,
_taskController.taskList[index],
);
},
child: TaskTile(
_taskController.taskList[index],
),
)
],
),
),
),
);
},
);
},
),
);
}
_showBottomSheet(BuildContext context, Task task) {
Get.bottomSheet(
Container(
padding: const EdgeInsets.only(top: 3),
height: task.isCompleted == 1
? MediaQuery.of(context).size.height * 0.25
: MediaQuery.of(context).size.height * 0.35,
color: Colors.white,
),
);
}
_bottomSheetButton({
required String label,
required Function()? onTap,
required Color color,
bool isClose = false,
required BuildContext context,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4),
height: 55,
width: MediaQuery.of(context).size.width * 0.9,
decoration: BoxDecoration(
border: Border.all(
width: 2,
color: isClose == true ? Colors.red : color,
),
borderRadius: BorderRadius.circular(20),
color: isClose == true ? Colors.red : color,
),
),
);
}
}
When I'm clicking on container it throwing an exception saying:
_CastError (Null check operator used on a null value)
I didn't use any null operators in here
Is this a problem with Get.bottomsheet method or what?<br?
Exception showing _showBottomSheet has something wrong I mean null operator or whatever
Can you please help me go through this?
in your method _showBottomSheet, Task is required variable.
_taskController.taskList[index] -> this is probably null, you should debug this.
In your method, you can set Task as optional, like this: Task? task, and call your method like this:
_showBottomSheet(
context,
_taskController.taskList?[index],
);
and then:
_showBottomSheet(BuildContext context, Task? task) {
Get.bottomSheet(
Container(
padding: const EdgeInsets.only(top: 3),
height: task?.isCompleted == 1
? MediaQuery.of(context).size.height * 0.25
: MediaQuery.of(context).size.height * 0.35,
color: Colors.white,
),
);
}
Related
I added an Navigation bar to the bottom of the app and discovered the error. I tried wrapping a bunch of widgets with scroll view mainaxisalignment, expanded and tried different methods that i saw on youtube or on Stack Overflow Overflowed by Infinity Pixels
The code for the Home page and navigation bar:
import 'package:date_picker_timeline/date_picker_timeline.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:ride/controllers/task_controller.dart';
import 'package:ride/services/theme_services.dart';
import 'package:ride/ui/add_task_bar.dart';
import 'package:ride/ui/theme.dart';
import 'package:ride/ui/widgets/button.dart';
import 'package:ride/ui/widgets/task_tile.dart';
import '../models/task.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final int _selectedIndex = 0;
static const List<Widget> _widgetOptions = <Widget>[
AddTaskPage(),
];
DateTime _selectedDate = DateTime.now();
final _taskController = Get.put(TaskController());
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _appbar(),
backgroundColor: context.theme.colorScheme.background,
body:
Column(children: [
_addTaskBar(),
_addDateBar(),
_widgetOptions.elementAt(_selectedIndex),
_showTasks(),
]),
);
}
_showTasks() {
return Expanded(
child: Obx(() {
return ListView.builder(
itemCount: _taskController.taskList.length,
itemBuilder: (_, index) {
Task task = _taskController.taskList[index];
//print(task.toJson());
if (task.date == DateFormat.yMd().format(_selectedDate)) {
return AnimationConfiguration.staggeredList(
position: index,
child: SlideAnimation(
child: FadeInAnimation(
child: Row(
children: [
GestureDetector(
onTap: () {
_showBottomSheet(context, task);
},
child: TaskTile(task),
)
],
))));
} else {
return Container();
}
});
}),
);
}
_showBottomSheet(BuildContext context, Task task) {
Get.bottomSheet(
Container(
padding: const EdgeInsets.only(top: 4),
height: task.isCompleted == 1
? MediaQuery.of(context).size.height * 0.24
: MediaQuery.of(context).size.height * 0.32,
color: Get.isDarkMode ? Colors.grey[850] : Colors.white,
child: Column(children: [
Container(
height: 6,
width: 120,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.grey[600]),
),
const Spacer(),
task.isCompleted == 1
? Container()
: _bottomSheetButton(
label: "Join",
onTap: () {
_taskController.markTaskCompleted(task.id!);
Get.back();
},
clr: primaryClr,
context: context),
_bottomSheetButton(
label: "Delete",
onTap: () {
_taskController.delete(task);
Get.back();
},
clr: Colors.red[400]!,
context: context),
const SizedBox(
height: 20,
),
_bottomSheetButton(
label: "Close",
onTap: () {
Get.back();
},
clr: Colors.red[400]!,
isClose: true,
context: context),
const SizedBox(height: 10),
]),
),
);
}
_bottomSheetButton({
required String label,
required Function()? onTap,
required Color clr,
bool isClose = false,
required BuildContext context,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4),
height: 55,
width: MediaQuery.of(context).size.width * 0.9,
decoration: BoxDecoration(
border: Border.all(
width: 2,
color: isClose == true
? Get.isDarkMode
? Colors.grey[600]!
: Colors.grey[400]!
: clr),
borderRadius: BorderRadius.circular(20),
color: isClose == true ? Colors.transparent : clr,
),
child: Center(
child: Text(
label,
style:
isClose ? titleStyle : titleStyle.copyWith(color: Colors.white),
)),
),
);
}
_addDateBar() {
return Container(
margin: const EdgeInsets.only(
top: 20,
left: 20,
),
child: DatePicker(
DateTime.now(),
height: 100,
width: 80,
initialSelectedDate: DateTime.now(),
selectionColor: primaryClr,
selectedTextColor: Colors.white,
dateTextStyle: GoogleFonts.lato(
textStyle: const TextStyle(
fontSize: 20, fontWeight: FontWeight.w600, color: Colors.grey),
),
dayTextStyle: GoogleFonts.lato(
textStyle: const TextStyle(
fontSize: 16, fontWeight: FontWeight.w600, color: Colors.grey),
),
monthTextStyle: GoogleFonts.lato(
textStyle: const TextStyle(
fontSize: 14, fontWeight: FontWeight.w600, color: Colors.grey),
),
onDateChange: (date) {
setState(() {
_selectedDate = date;
});
},
),
);
}
_addTaskBar() {
return Container(
margin: const EdgeInsets.only(right: 20, top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
margin: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
DateFormat.yMMMMd().format(DateTime.now()),
style: subHeadingStyle,
),
Text(
'Today',
style: headingStyle,
)
],
),
),
MyButton(
label: "+ Add",
onTap: () async {
await Get.to(const AddTaskPage());
_taskController.getTasks();
})
],
),
);
}
_appbar() {
return AppBar(
elevation: 0,
backgroundColor: context.theme.colorScheme.background,
leading: GestureDetector(
onTap: () {
ThemeService().switchTheme();
},
child: Icon(
Get.isDarkMode
? Icons.wb_sunny_outlined
: Icons.dark_mode_outlined,
size: 30,
color: Get.isDarkMode ? Colors.white : Colors.black),
),
actions: [
Icon(Icons.person_outline,
size: 30, color: Get.isDarkMode ? Colors.white : Colors.black),
const SizedBox(
width: 15,
)
]);
}
}
main.dart:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';
import 'package:ride/login/login.dart';
import 'package:ride/services/theme_services.dart';
import 'package:ride/ui/home_page.dart';
import 'package:ride/ui/theme.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
final isLoggedIn = prefs.getBool('isLoggedIn') ?? false;
await Firebase.initializeApp();
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp(isLoggedIn: isLoggedIn));
}
class MyApp extends StatelessWidget {
final bool isLoggedIn;
const MyApp({super.key, required this.isLoggedIn});
//Root of Application
#override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: Themes.light,
darkTheme: Themes.dark,
themeMode: ThemeService().theme,
home: isLoggedIn ? const HomePage() : LogIn());
}
}
I tried Wrapping the Container and SafeArea widgets in the Expanded widget and tried wrapping the same widgets with SingleChildScrollView AND wrapped the 2 widgets with Expanded AND SingleChildScrollView but nothing worked.
I fixed it!! I removed _widgetOptions.elementAt(_selectedIndex) and all errors are gone.
I'd like to use Map for my app.
I'm using Flutter.
I don't understand why there is an error when I use map on onChanged part!
this is code I use
I really don't understand why it doesn't work
the lists in the mapItem are from global list so I think it's not the problem.
and also it doesn't make an error
is there any way to fix it?
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:get/get.dart';
import 'package:youtube_ad2/provider/food_name.dart';
import 'result_screen.dart';
import 'package:youtube_ad2/provider/food_provider.dart';
import 'package:provider/provider.dart';
class HomePage extends StatefulWidget {
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
InterstitialAd? interstitialAd;
bool isLoaded = false;
#override
void initState() {
super.initState();
Provider.of<Category>(context, listen: false);
}
#override
void didChangeDependencies() {
//TODO implement didChangeDependencies
super.didChangeDependencies();
InterstitialAd.load(
adUnitId: InterstitialAd.testAdUnitId,
request: AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (ad) {
setState(() {
isLoaded = true;
interstitialAd = ad;
});
print("Ad Loaded");
},
onAdFailedToLoad: (error) {
print("Interstitial Failed to load");
},
),
);
}
Map<String,List> mapItem = {
'전체': total,
"중국": chn,
"한국": kor,
"일본": jpn,
"동남아": asia,
"유럽": eu,
"아메리카": america,
'오세아니아': aus,
};
String? value;
List<String> listItem = [
"전체",
"중국",
"한국",
"일본",
"동남아",
"유럽",
"아메리카",
'오세아니아',
];
#override
Widget build(BuildContext context) {
return Container(
// decoration: BoxDecoration(
// image: DecorationImage(
// fit: BoxFit.cover,
// image: AssetImage('assets/images/bg3.png'), // 배경 이미지
// ),
// ),
child: Scaffold(
backgroundColor: Colors.orange[300],
appBar: AppBar(
automaticallyImplyLeading: false,
elevation: 0,
title: Center(
child: Text(
'오늘의 식사',
style: TextStyle(
fontFamily: 'Chilgok',
color: Colors.yellow.shade300,
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
ElevatedButton(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/images/logo.png',
width: MediaQuery.of(context).size.width / 3,
),
Text('Open!'),
]),
style: ElevatedButton.styleFrom(
side: BorderSide(
width: 5,
color: Colors.red,
),
elevation: 40,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100)),
primary: Colors.orange[300],
padding: const EdgeInsets.only(
top: 9,
bottom: 15,
left: 20,
right: 20,
),
),
onPressed: () {
if (isLoaded) {
interstitialAd!.show();
Get.to(() => ResultScreen());
} else {
Get.to(() => ResultScreen());
}
},
),
Container(
padding: EdgeInsets.only(
left: 10,
right: 10,
top: 3,
bottom: 5,
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15),
border: Border.all(
color: Colors.red,
width: 4,
),
),
width: MediaQuery.of(context).size.width / 3,
height: 40,
child: DropdownButton<String>(
underline: DropdownButtonHideUnderline(child: Container()),
dropdownColor: Colors.grey[200],
borderRadius: BorderRadius.circular(10),
elevation: 0,
hint: Text(
"음식종류",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17,
),
),
value: value,
iconSize: 20,
icon: Icon(Icons.arrow_drop_down, color: Colors.red),
isExpanded: true,
items: listItem.map(valueItem).toList(),
onChanged: (value) {setState(() => this.value = value);
context.read<Category>().selectCategory(mapItem(this.value));
},
),
)
],
),
)),
);
}
DropdownMenuItem<String> valueItem(String item) => DropdownMenuItem(
value: item,
child: Text(
item,
style: TextStyle(
color: Colors.black87,
fontSize: 20,
),
),
);
}
to find this more easier I will post an image too
You are accessing the value of a Map wrong. You have to use square brackets to access the value of a Map by providing the key. Here is an example.
final Map<String, dynamic> map = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4',
};
print(map['key1']); // Prints value1
For your case
context.read<Category>().selectCategory(mapItem[this.value]);
import 'package:e_comaece/widget/back_layer.dart';
import 'package:flutter/material.dart';
import 'package:backdrop/backdrop.dart';
import 'package:carousel_pro_nullsafety/carousel_pro_nullsafety.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
class Home extends StatefulWidget {
static const routeName = "/home";
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
final List<Widget> _CarouselImage = [
Image.asset('images/caro1.png'),
Image.asset('images/caro2.png'),
Image.asset('images/caro3.png'),
Image.asset('images/caro4.png'),
];
final List _swipImage = [
Image.asset('images/addidas.jpeg'),
Image.asset('images/apple.jpeg'),
Image.asset('images/Dell.jpeg'),
Image.asset('images/h&m.jpeg'),
Image.asset('images/Huawei.jpeg'),
Image.asset('images/nike.jpeg'),
Image.asset('images/samsung.jpeg'),
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: BackdropScaffold(
headerHeight: MediaQuery.of(context).size.height * 0.1,
appBar: BackdropAppBar(
title: const Text(
'EasyBuy',
style: TextStyle(
fontSize: 20, fontStyle: FontStyle.italic, color: Colors.white),
),
leading: BackdropToggleButton(
icon: AnimatedIcons.home_menu,
),
actions: [
IconButton(
onPressed: () {},
icon: CircleAvatar(
radius: 14,
backgroundImage: NetworkImage(
"https://cdn1.vectorstock.com/i/1000x1000/43/20/bearded-man-s-face-hipster-character-fashion-vector-18884320.jpg"),
),
)
],
),
backLayer: const BackLayer(),
frontLayer: ListView(
children: [
Container(
width: double.infinity,
height: 150,
child: Carousel(
images: _CarouselImage,
autoplay: true,
animationDuration: Duration(milliseconds: 5),
animationCurve: Curves.fastOutSlowIn,
indicatorBgPadding: 4,
dotSize: 5,
boxFit: BoxFit.fill,
)),
const SizedBox(
height: 5,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Popular Brands',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
),
TextButton(
onPressed: () {},
child: const Text('view all',
style: TextStyle(fontWeight: FontWeight.w400)),
)
],
),
),
const SizedBox(
height: 10,
),
//type 'Image' is not a subtype of type 'String'
Container(
height: 150,
width: double.infinity,
child: Swiper(
itemCount: _swipImage.length,
itemBuilder: (ctx, int i) {
return Container(
decoration: BoxDecoration(
border: Border.all(width: 2, color: Colors.grey),
borderRadius: BorderRadius.circular(12.0),
),
child: Image.asset(_swipImage[i]),
);
},
))
],
),
),
);
}
}
The error message is actually quite self-explanatory.
Your code is expecting _swipImage[i] to be a List of Strings List<String>, instead of a list of image assets List<AssetImage>.
Change this code:
final List<Widget> _CarouselImage = [
Image.asset('images/caro1.png'),
Image.asset('images/caro2.png'),
Image.asset('images/caro3.png'),
Image.asset('images/caro4.png'),
];
final List _swipImage = [
Image.asset('images/addidas.jpeg'),
Image.asset('images/apple.jpeg'),
Image.asset('images/Dell.jpeg'),
Image.asset('images/h&m.jpeg'),
Image.asset('images/Huawei.jpeg'),
Image.asset('images/nike.jpeg'),
Image.asset('images/samsung.jpeg'),
];
into a list of Strings, like this:
final List<String> _CarouselImage = [
'images/caro1.png',
'images/caro2.png',
]
i assume this is your code.
Container(
child: Swiper(
itemBuilder: (ctx, init i) {
return Container(
child: Image.asset(_swipImage[i])
)
}
Your code using two Image.asset in last line.
child: Image.asset(Image.asset('images/addidas.jpeg'))
change it to this:
Container(
child: Swiper(
itemBuilder: (ctx, init i) {
return Container(
child: _swipImage[i],
)
}
I concede that there are many questions similar to mine, but I have not found a satisfactory answer from those questions. So I decided to make my own question specifying my problem. I have 3 BloCs in my program each with different purposes. They all share similar problems, as such I will ask on one of those BloCs with the hope that one solution will fix all of the BloCs.
The problem is this, if I just started the application and have logged in, the BloC will update the UI. If I have logged in, exited the app, and restarted it, the Bloc will not update the UI. The Bloc in question is called DetailpersonilBloc with 1 event called Detail and 2 states called DetailpersonilInitial and Loaded. At the event of Detail, the state Loaded should be emitted.
I called Detail at LoginPage and at GajiPage at initState. This works when I just opened the app, but does not work when I restart the app. I also have equatable thinking that it will help me but apparently it changes nothing.
Note: The "..." at the GajiPage is just some code that I believe is not necessary for reproduction.
DetailpersonilBloc
part 'detailpersonil_event.dart';
part 'detailpersonil_state.dart';
class DetailpersonilBloc
extends Bloc<DetailpersonilEvent, DetailpersonilState> {
DetailpersonilBloc() : super(const DetailpersonilInitial()) {
on<Detail>((event, emit) async {
SharedPreferences pref = await SharedPreferences.getInstance();
String name = pref.getString('nama');
String nrp = pref.getString('NRP');
String pangkat = pref.getString('pangkat');
String jabatan = pref.getString('jabatan');
String satker = pref.getString('satker');
String polda = pref.getString('polda');
String npwp = pref.getString('NPWP');
String rekening = pref.getString('rekening');
String bank = pref.getString('bank');
emit(Loaded(
name,
nrp,
pangkat,
jabatan,
satker,
polda,
npwp,
rekening,
bank,
));
});
}
}
DetailpersonilEvent
part of 'detailpersonil_bloc.dart';
#immutable
abstract class DetailpersonilEvent extends Equatable {}
class Detail extends DetailpersonilEvent {
#override
List<Object> get props => [];
}
DetailpersonilState
part of 'detailpersonil_bloc.dart';
#immutable
abstract class DetailpersonilState extends Equatable {
final String nama;
final String nrp;
final String pangkat;
final String jabatan;
final String satker;
final String polda;
final String npwp;
final String rekening;
final String bank;
const DetailpersonilState(
{this.nama,
this.nrp,
this.pangkat,
this.jabatan,
this.satker,
this.polda,
this.npwp,
this.rekening,
this.bank});
}
class DetailpersonilInitial extends DetailpersonilState {
const DetailpersonilInitial()
: super(
nama: 'Nama',
nrp: 'NRP',
pangkat: 'Pangkat',
jabatan: 'Jabatan',
satker: 'Satker',
polda: 'Polda',
npwp: 'NPWP',
rekening: 'No Rekening',
bank: 'Nama Bank',
);
#override
List<Object> get props =>
[nama, nrp, pangkat, jabatan, satker, polda, npwp, rekening, bank];
}
class Loaded extends DetailpersonilState {
const Loaded(
String nama,
String nrp,
String pangkat,
String jabatan,
String satker,
String polda,
String npwp,
String rekening,
String bank,
) : super(
nama: nama,
nrp: nrp,
pangkat: pangkat,
jabatan: jabatan,
satker: satker,
polda: polda,
npwp: npwp,
rekening: rekening,
bank: bank);
#override
List<Object> get props =>
[nama, nrp, pangkat, jabatan, satker, polda, npwp, rekening, bank];
}
LoginPage
class LoginPage extends StatefulWidget {
const LoginPage({Key key}) : super(key: key);
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
double width = 0;
double height = 0;
TextEditingController nrpController = TextEditingController();
TextEditingController sandiController = TextEditingController();
final formKey = GlobalKey<FormState>();
DetailpersonilBloc detailPersonilBloc;
GajiBloc gajiBloc;
TunkinBloc tunkinBloc;
bool passwordVisible = false;
#override
void initState() {
super.initState();
checkToken();
}
void checkToken() async {
SharedPreferences pref = await SharedPreferences.getInstance();
if (pref.getString('token') != null) {
detailPersonilBloc = DetailpersonilBloc();
gajiBloc = GajiBloc();
tunkinBloc = TunkinBloc();
detailPersonilBloc.add(Detail());
gajiBloc.add(Gaji());
tunkinBloc.add(Tunkin());
Navigator.push(
context, MaterialPageRoute(builder: (context) => const MainPage()));
}
}
onLogin(DetailpersonilBloc detailPersonilBloc) async {
if (formKey.currentState.validate()) {
var token = await APIService.generateToken(
nrpController.text, sandiController.text);
if (token != null) {
SharedPreferences pref = await SharedPreferences.getInstance();
await pref.setString('token', token.token);
var detail = await APIService.getDetailPersonil(token.token);
await pref.setString('nama', detail.nMPEG);
await pref.setString('NRP', detail.nRP);
await pref.setString('pangkat', detail.nMGOL1);
await pref.setString('jabatan', detail.sEBUTJAB);
await pref.setString('satker', detail.nMSATKER);
await pref.setString('polda', detail.nMUAPPAW);
await pref.setString('NPWP', detail.nPWP);
await pref.setString('rekening', detail.rEKENING);
await pref.setString('bank', detail.nMBANK);
nrpController.clear();
sandiController.clear();
detailPersonilBloc.add(Detail());
Navigator.push(
context, MaterialPageRoute(builder: (context) => const MainPage()));
} else {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Error'),
content: Text('Login Gagal'),
actions: [
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Tutup'),
),
],
);
},
);
}
}
}
#override
Widget build(BuildContext context) {
var detailPersonilBloc = BlocProvider.of<DetailpersonilBloc>(context);
width = MediaQuery.of(context).size.width;
height = MediaQuery.of(context).size.height;
return Scaffold(
body: Stack(
children: [
Column(
mainAxisAlignment: MainAxisAlignment.end,
children: const [
Opacity(
opacity: 0.5,
child: Image(
image: AssetImage('images/bg-map-min.png'),
),
),
],
),
SingleChildScrollView(
padding: EdgeInsets.only(top: 100),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
height: 100,
width: width,
child: const Image(
image: AssetImage('images/login-logo.png'),
alignment: Alignment.center,
),
),
Container(
padding: const EdgeInsets.all(15),
child: const Text(
'GAJI DAN TUNKIN',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
Form(
key: formKey,
child: Column(
children: [
Container(
margin: const EdgeInsets.all(20 - 2.6),
child: Card(
elevation: 10,
child: Container(
padding: const EdgeInsets.all(20),
child: Column(
children: [
Container(
alignment: Alignment.topLeft,
padding: const EdgeInsets.only(bottom: 20),
child: const Text(
'LOGIN',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
Container(
padding: const EdgeInsets.only(bottom: 25),
child: TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Masukkan NRP/NIP';
}
return null;
},
controller: nrpController,
decoration: InputDecoration(
labelText: 'NRP/NIP',
hintText: 'Masukkan NRP/NIP',
prefixIcon: Icon(Icons.person,
color: Colors.blue.shade700),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
),
TextFormField(
obscureText: !passwordVisible,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Masukkan Kata Sandi';
}
return null;
},
controller: sandiController,
decoration: InputDecoration(
labelText: 'Kata Sandi',
hintText: 'Masukkan Kata Sandi',
prefixIcon: Icon(Icons.lock,
color: Colors.blue.shade700),
suffixIcon: IconButton(
onPressed: () {
setState(() {
passwordVisible = !passwordVisible;
});
},
icon: Icon(
passwordVisible
? Icons.visibility
: Icons.visibility_off,
color: Colors.blue.shade700,
),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
)
],
),
),
),
),
ElevatedButton(
onPressed: () async {
await onLogin(detailPersonilBloc);
},
child: const Text('LOGIN'),
style: ElevatedButton.styleFrom(
primary: Colors.blue.shade700,
minimumSize: const Size(200, 40),
),
)
],
),
),
],
),
),
],
),
);
}
}
GajiPage
class GajiPage extends StatefulWidget {
const GajiPage({Key key}) : super(key: key);
#override
_GajiPageState createState() => _GajiPageState();
}
class _GajiPageState extends State<GajiPage> {
double width = 0;
double height = 0;
var currentYear = DateTime.now().year;
var currentMonth = DateTime.now().month;
DetailpersonilBloc detailPersonilBloc;
GajiBloc gajiBloc;
#override
void initState() {
setState(() {
detailPersonilBloc = DetailpersonilBloc();
detailPersonilBloc.add(Detail());
setMonth();
setYear();
gajiBloc = GajiBloc();
gajiBloc.add(Gaji());
});
super.initState();
}
#override
Widget build(BuildContext context) {
var detailPersonilBloc = BlocProvider.of<DetailpersonilBloc>(context);
width = MediaQuery.of(context).size.width;
height = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Image(
image: const AssetImage('images/header-logo.png'),
width: width / 2,
),
flexibleSpace: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Color.fromARGB(255, 170, 177, 175),
Color.fromARGB(255, 197, 217, 212)
],
),
),
),
),
body: Stack(
children: [
BlocBuilder<GajiBloc, GajiState>(
builder: (context, state) {
return state is GajiLoaded
? ListView(
children: [
Container(
height: 100,
),
Card(
color: const Color.fromARGB(255, 74, 50, 152),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: const EdgeInsets.all(10),
child: const Text(
'Gaji Bersih',
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
),
Container(
margin: const EdgeInsets.all(10),
child: Text(
NumberFormat.currency(
locale: 'en',
symbol: 'RP ',
decimalDigits: 0)
.format(state.bersih),
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 40,
color: Colors.white,
),
),
),
],
),
),
Card(
child: Column(
children: [
Container(
color: const Color.fromARGB(255, 238, 238, 238),
width: width,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Container(
margin: const EdgeInsets.fromLTRB(
10, 10, 0, 10),
width: (width / 2) - 25,
child: const Text(
'Detail Gaji',
textAlign: TextAlign.start,
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 20,
),
),
),
Container(
margin: const EdgeInsets.fromLTRB(
5, 10, 20, 10),
width: (width / 2) - 18,
child: Text(
'${state.bulan} - ${state.tahun}',
textAlign: TextAlign.end,
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 20,
),
),
)
],
),
),
...
],
),
),
Container(
height: 50,
),
],
)
: Center(
child: Text(
'Tidak ada data. Data gaji bulan ${state.bulan} belum diproses'),
);
},
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Center(
child: BlocBuilder<DetailpersonilBloc, DetailpersonilState>(
builder: (context, state) {
return Card(
child: Row(
children: [
Container(
margin: const EdgeInsets.all(10),
child: const CircleAvatar(
backgroundImage: AssetImage('images/Profpic.PNG'),
radius: 30,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 250,
padding: const EdgeInsets.all(5),
child: Text(
state.nama,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold),
)),
Container(
padding: const EdgeInsets.all(5),
child: Text(
state.nrp,
style: const TextStyle(fontSize: 15),
)),
],
),
GestureDetector(
onTap: () {
detailPersonilBloc.add(Detail());
showModalBottomSheet(
backgroundColor: Colors.transparent,
isScrollControlled: true,
context: context,
builder: (context) => detailsBottomSheet(),
);
},
child: const Text(
'DETAILS',
style: TextStyle(color: Colors.blue),
),
)
],
),
);
},
),
),
GestureDetector(
onTap: () {
showModalBottomSheet(
backgroundColor: Colors.transparent,
isScrollControlled: true,
context: context,
builder: (context) {
return StatefulBuilder(
builder: (context, StateSetter setState) {
return filterBottomSheet();
},
);
},
);
},
child: Container(
height: 50,
width: width,
decoration: const BoxDecoration(
color: Color.fromARGB(255, 244, 244, 244),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
margin: const EdgeInsets.only(right: 3),
child: const Icon(
Icons.tune,
color: Color.fromARGB(255, 45, 165, 217),
),
),
const Text(
'Filter',
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 20,
color: Color.fromARGB(255, 45, 165, 217),
),
),
],
),
),
)
],
)
],
),
);
}
}
Note 2: The "..." is a bunch of code not needed for reproduction.
The answer is surprisingly simple as I would learn from my internship. The reason the Bloc is not updating is because I was not using the context of the application. So when I generated a new Bloc inside my pages, it was "empty". So the solution is to use context.read().add(BlocEvent()) or create a new bloc with BlocProvider.of(context) then add the event. Basically the bloc has to be provided with the original context of the application.
import 'package:facebook_audience_network/ad/ad_native.dart';
import 'package:facebook_audience_network/facebook_audience_network.dart';
import 'package:flutter/material.dart';
import 'package:share/share.dart';
import 'package:social_share/social_share.dart';
import 'package:clipboard_manager/clipboard_manager.dart';
// ignore: camel_case_types
class listview extends StatefulWidget {
const listview({
Key key,
#required this.records,
}) : super(key: key);
final List records;
#override
_listviewState createState() => _listviewState();
}
// ignore: camel_case_types
class _listviewState extends State<listview> {
#override
void initState() {
super.initState();
FacebookAudienceNetwork.init(
testingId: "35e92a63-8102-46a4-b0f5-4fd269e6a13c",
);
// _loadInterstitialAd();
// _loadRewardedVideoAd();
}
// ignore: unused_field
Widget _currentAd = SizedBox(
width: 0.0,
height: 0.0,
);
Widget createNativeAd() {
_showNativeAd() {
_currentAd = FacebookNativeAd(
adType: NativeAdType.NATIVE_AD,
backgroundColor: Colors.blue,
buttonBorderColor: Colors.white,
buttonColor: Colors.deepPurple,
buttonTitleColor: Colors.white,
descriptionColor: Colors.white,
width: double.infinity,
height: 300,
titleColor: Colors.white,
listener: (result, value) {
print("Native Ad: $result --> $value");
},
);
}
return Container(
width: double.infinity,
height: 300,
child: _showNativeAd(),
);
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: this.widget.records.length,
itemBuilder: (BuildContext context, int index) {
var card = Container(
child: Card(
margin: EdgeInsets.only(bottom: 10),
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(1.0),
),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
print(this.widget.records);
},
child: Image.asset(
"assets/icons/avatar.png",
height: 45,
),
),
),
Padding(
padding: const EdgeInsets.only(left: 5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
(this
.widget
.records[index]['fields']['Publisher Name']
.toString()),
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(
(this
.widget
.records[index]['fields']['Date']
.toString()),
style: TextStyle(
fontSize: 12,
),
),
],
),
)
],
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: MediaQuery.of(context).size.width * 0.90,
// height: MediaQuery.of(context).size.height * 0.20,
decoration: BoxDecoration(
border: Border.all(
color: Colors.purple,
width: 3.0,
),
),
child: Center(
child: Padding(
padding: const EdgeInsets.all(18.0),
child: Text(
(this
.widget
.records[index]['fields']['Shayari']
.toString()),
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
),
),
),
),
),
),
SizedBox(
height: 5,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
GestureDetector(
onTap: () {
ClipboardManager.copyToClipBoard(this
.widget
.records[index]['fields']['Shayari']
.toString())
.then((result) {
final snackBar = SnackBar(
content: Text('Copied to Clipboard'),
);
Scaffold.of(context).showSnackBar(snackBar);
});
print(this
.widget
.records[index]['fields']['Shayari']
.toString());
},
child: Image.asset(
"assets/icons/copy.png",
height: 25,
),
),
GestureDetector(
onTap: () async {
SocialShare.checkInstalledAppsForShare().then(
(data) {
print(data.toString());
},
);
},
child: Image.asset(
"assets/icons/whatsapp.png",
height: 35,
),
),
GestureDetector(
onTap: () async {
Share.share("Please Share https://google.com");
},
child: Image.asset(
"assets/icons/share.png",
height: 25,
),
),
],
),
SizedBox(
height: 5,
),
],
),
),
);
return Column(
children: [
card,
index != 0 && index % 5 == 0
? /* Its Show When Value True*/ createNativeAd()
: /* Its Show When Value false*/ Container()
],
);
},
);
}
}
I Am Having This Error setState() or markNeedsBuild() called during build.
I Try To Call Facebook Native Ads Between My Dynamic List View But Showing this error when I call native ad createNativeAd This is My Widget Where I set Native ad
This is code where I call ad
** return Column(
children: [
card,
index != 0 && index % 5 == 0
? /* Its Show When Value True*/ createNativeAd()
: /* Its Show When Value false*/ Container()
],
);
},
);**