Flutter - facing issue on defined context, build context - flutter

I'm new to Flutter for a month. Currently I'm facing below issue where showing undefined name 'context'. I have follow the suggestion to import 'dart:js' and it show error "The argument type 'JsObject' can't be assigned to the parameter type 'BuildContext'."
import 'package:dparking/reusable_widgets/reusable_widget.dart';
import 'package:dparking/screens/signup_screen.dart';
import 'package:flutter/material.dart';
class SignInScreen extends StatefulWidget {
const SignInScreen({Key? key}) : super(key: key);
#override
State<SignInScreen> createState() => _SignInScreenState();
}
class _SignInScreenState extends State<SignInScreen> {
final TextEditingController _passwordTextController = TextEditingController();
final TextEditingController _emailTextController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
decoration: const BoxDecoration(
gradient: LinearGradient(colors: [
Colors.blue,
Colors.green,
], begin: Alignment.topCenter, end: Alignment.bottomCenter)),
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.fromLTRB(
20, MediaQuery.of(context).size.height * 0.2, 20, 0),
child: Column(
children: <Widget>[
logoWidget("assets/images/DParking.png"),
const SizedBox(
height: 30,
),
reusableTextField("Enter UserName", Icons.person_outline, false,
_emailTextController),
const SizedBox(
height: 20,
),
reusableTextField("Enter Password", Icons.lock_outline, true,
_passwordTextController),
const SizedBox(
height: 20,
),
signInSignUpButton(context, true, () {}),
signUpOption()
],
),
),
),
),
);
}
}
Row signUpOption() {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Don't have account?",
style: TextStyle(color: Colors.white70)),
GestureDetector(
onTap: () {
Navigator.push(context, //<- error on this line
MaterialPageRoute(builder: (context) => SignUpScreen()));
},
child: const Text(
" Sign Up",
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
)
],
);
}
Please give me some advice on how can I solve this issue. thank you.

You should pass the context as the signUpOption argument.
signUpOption(context)
],
...
Row signUpOption(BuildContext context) {
...
}
Or move the function into the _SignInScreenState class for using the context of the State.

Related

The problem happens in the ListView.builder which the card can't clip at the top

The problem happens in the ListView.builder which the card can't clip at the top.Is my code have anything missing? How can I do?
The problem happens in the ListView.builder which the card can't clip at the top. Is my code have anything missing? How can I do?
The problem happens in the ListView.builder which the card can't clip at the top. Is my code have anything missing? How can I do?
There are a space between the card and with the top
[1]: https://i.stack.imgur.com/fpJ4h.png
This is what I want and expected
[2]: https://i.stack.imgur.com/aAhmh.png
This is the AllProduct.dart
import 'package:flutter/material.dart';
import 'package:penang_beachess/blog_page/blog_page.dart';
import 'package:penang_beachess/provider/favorite_list.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:penang_beachess/widget/background-image.dart';
import 'package:provider/provider.dart';
import '../widget/background.dart';
class AllBlog extends StatefulWidget {
const AllBlog({Key? key}) : super(key: key);
#override
State<AllBlog> createState() => _AllBlogState();
}
class _AllBlogState extends State<AllBlog> {
bool _isBookmarked(Beach newAddBeach) {
List favoritedBeach = favoriteBeachList;
if (favoritedBeach.contains(newAddBeach)) {
return true;
}
return false;
}
#override
Widget build(BuildContext context) {
var favoriteList = Provider.of<favoriteProvider>(context);
return Stack(
children: [
//problem Here
ListView.builder(
itemCount: beachList.length,
itemBuilder: (context, index) {
Beach beach = beachList[index];
int currentIndex = index;
return Card(
child: ListTile(
title: Text(beach.title,
style: GoogleFonts.permanentMarker(
textStyle: TextStyle(fontSize: 15),
)),
subtitle: Row(
children: [
const Icon(
Icons.location_on,
size: 16.0,
),
Text(
beach.location,
style: GoogleFonts.permanentMarker(
textStyle: TextStyle(fontSize: 12.0),
),
overflow: TextOverflow.ellipsis,
),
],
),
leading: SizedBox(
height: 80,
width: 80,
child: Image.asset(beach.urlToImage1),
),
// add bookmark here
trailing: IconButton(
onPressed: () {
if (!_isBookmarked(beach)) {
setState(() {
favoriteBeachList.add(beachList[currentIndex]);
});
} else {
setState(() {
favoriteBeachList.remove(beachList[currentIndex]);
});
}
Beach _beach = Beach(
title: beachList[index].title,
location: beachList[index].location,
source: beachList[index].source,
author: beachList[index].author,
description: beachList[index].description,
urlToImage1: beachList[index].urlToImage1,
urlToImage2: beachList[index].urlToImage2,
facilities: beachList[index].facilities,
urlToImage3: beachList[index].urlToImage3,
status: beachList[index].status,
likeCount: beachList[index].likeCount,
);
if (_beach.status == 'false') {
setState(() {
beachList[index].status = 'true';
});
favoriteList.addToList(_beach);
} else if (_beach.status == 'true') {
setState(() {
beachList[index].status = 'false';
});
favoriteList.removeFromList(_beach);
}
},
icon: Icon(_isBookmarked(beach)
? Icons.bookmark
: Icons.bookmark_border),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BlogPage(beach)));
}),
);
}),
],
);
}
}
This is Home.dart
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'package:two_life/model/product.dart';
import 'package:two_life/model/provider.dart/favorite_list.dart';
import 'package:two_life/screens/ReProductDetail.dart/Re3.dart';
import 'package:two_life/screens/allproduct.dart';
import 'package:two_life/screens/homepagecard.dart';
import 'package:two_life/screens/productDetails.dart';
import 'ReProductDetail.dart/Re1.dart';
import 'ReProductDetail.dart/Re2.dart';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Color.fromRGBO(211, 211, 211, 1),
child: Align(
alignment: Alignment.center,
child: Column(
children: [
SizedBox(
height: 70,
),
Container(
width: 350,
height: 100,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(30),
),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Text(
"Welcome to 2.LIFE!\n\n Enjoy your shopping with us via 2.LIFE!!",
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 17)),
),
),
SizedBox(
height: 15,
),
Container(
width: 350,
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Text("Recommended",
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 17)),
),
),
Container(
child: listview(),
),
Container(
width: 350,
height: 30,
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Text("All Product",
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 17)),
),
),
// Here is the SizedBox for the AllProduct in AllProduct.dart
SizedBox(
height: 280,
child: AllProduct(),
),
],
),
),
));
}
}
class listview extends StatefulWidget {
const listview({super.key});
#override
State<listview> createState() => _listviewState();
}
class _listviewState extends State<listview> {
#override
Widget build(BuildContext context) {
return Container(
height: 200,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
//Product 1
Padding(
......

Flutter: Positional arguments must occur before named arguments. Try moving all of the positional arguments before the named arguments

I tried solving it but I can't find out what went wrong. All I did was add the listener argument in the AuthButton that is going to the onPressed. AuthButton is also give below.
import 'package:flutter/material.dart';
import '../widgets/buttons.dart';
import '../widgets/phonenumber_widget.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key);
#override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: SingleChildScrollView(
child: SizedBox(
width: double.infinity,
child: Column(
children: [
const SizedBox(
height: 40,
),
const Image(
image: AssetImage('assets/icon/brand_logo.png'),
width: 250,
),
const SizedBox(
height: 20,
),
const Text(
'Login',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: Color(0xFF191B32)),
),
const SizedBox(
height: 50,
),
const Text(
'Please enter your phone number to login with OTP',
style: TextStyle(
color: Colors.black26,
),
),
const SizedBox(
height: 20,
),
//Button
const PhoneNumberInput(),
const SizedBox(
height: 20,
),
AuthButton(
text: 'Request OTP', listener: () {Navigator.of(context).pushNamed('/otp');}),
),
const SizedBox(
height: 30,
),
Text('or, login with ...'),
const SizedBox(
height: 20,
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
SocialAuthButton(text: 'assets/icon/logo-google-50.png'),
SizedBox(
width: 30,
),
SocialAuthButton(
text: 'assets/icon/logo-facebook-50.png'),
],
),
),
const SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('New to Zigzag?'),
const SizedBox(
width: 5,
),
GestureDetector(
onTap: () {},
child: const Text(
'Sign up',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.purple,
),
),
),
],
),
],
),
),
),
),
);
}
}
AuthButton
class AuthButton extends StatelessWidget {
final String text;
final Function listener;
const AuthButton({Key? key, required this.text, required this.listener})
: super(key: key);
#override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.only(left: 20, right: 20),
child: MaterialButton(
onPressed: () {
listener(),
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 30),
minWidth: double.infinity,
child: Text(
text,
style: const TextStyle(
color: Colors.white,
),
),
),
);
}
}
Without knowing your function definition, but as the error message describes, it may like
void test(String required, {String optional = "default"}) {}
you should call it like
test("aa", optional: "specified");
not
test(optional: "specified", "aa");
in which the required variable is a positional argument and optional is an optional named argument.

Please Solve this problem .... "type 'Image' is not a subtype of type 'String"

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],
)
}

Why is Flutter BloC UI not updating after app restart despite state change in observer?

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.

Flutter error involving operator not defined

I'm new to flutter and I'm following this tutorial but I'm currently getting this error
error: The operator '[]' isn't defined for the type 'Map<String, dynamic> Function()'. (undefined_operator at [chat_app_tutorial] lib\views\search.dart:33)
Please I've been having this bug for over 2days now. I've checked here and I've been researching online but I've not seen anything that has worked so far. This is the line of code I'm getting the error from.
I'm not sure what part of my code is needed to be able to help me so I'll just put everything.
import 'package:chat_app_tutorial/widgets/widget.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class SearchScreen extends StatefulWidget {
#override
_SearchScreenState createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen> {
DatabaseMethods databaseMethods = new DatabaseMethods();
TextEditingController searchTextEditingController = new TextEditingController();
QuerySnapshot searchSnapshot;
initiateSearch(){
databaseMethods.getUserByUsername(searchTextEditingController.text).then((val){
setState(() {
searchSnapshot = val;
});
});
}
Widget searchList(){
return searchSnapshot != null ? ListView.builder(
itemCount: searchSnapshot.docs.length,
shrinkWrap: true,
itemBuilder: (context, index){
return SearchTile(
userName: searchSnapshot.docs[0].data["name"],
userEmail: searchSnapshot.docs[0].data["email"],
);
}
) : Container();
}
#override
void initState() {
initiateSearch();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: appBarMain(context),
body: SingleChildScrollView(
child: Container(
child: Column(
children: [
Container(
color: Color(0x54ffffff),
padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Row(
children: [
Expanded(
child: TextField(
controller: searchTextEditingController,
style: TextStyle(
color: Colors.white
),
decoration: InputDecoration(
hintText: "Search username",
hintStyle: TextStyle(
color: Colors.white54
),
border: InputBorder.none
),
),
),
GestureDetector(
onTap: (){
initiateSearch();
},
child: Container(
height: 40,
width: 40,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
const Color(0x36ffffff),
const Color(0x0fffffff)
]
),
borderRadius: BorderRadius.circular(40)
),
padding: EdgeInsets.all(12),
child: Image.asset("assets/images/search_white.png")
),
)
],
),
),
searchList()
],
),
),
),
);
}
}
class SearchTile extends StatelessWidget {
final String userName;
final String userEmail;
SearchTile({this.userName, this.userEmail});
#override
Widget build(BuildContext context) {
return Container(
child: Row(
children: [
Column(
children: [
Text(userName, style: simpleTextStyle(),),
Text(userEmail, style: simpleTextStyle(),)
],
),
Spacer(),
Container(
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(30)
),
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text("Message"),
)
],
),
);
}
}```
The error is complaining about:
return SearchTile(
userName: searchSnapshot.docs[0].data["name"],
userEmail: searchSnapshot.docs[0].data["email"],
);
searchSnapshot.docs[0].data is a function that returns a Map. You need to call that function first.
You probably want searchSnapshot.docs[0].data()['name'] and searchSnapshot.docs[0].data()['email'].
Even better would be to avoid calling data() multiple times:
var data = searchSnapshot.docs[0].data();
return SearchTile(userName: data['name'], userEmail: data['email']);