skip to Main Content

I want my user to be redirected to his own profile but I have a problem. This is an old code that I am trying to change and when user it is redirected to his own profile first it appears a sliding panel( with the story he uploaded) I want that sliding up panel to disappear and user to be send automatically to his own profile .. to understand better what I am saying I will let a video here : https://imgur.com/a/Y7t4Qs9

Here it’s the code for the homepage button:

             IconButton(
                  icon: const Icon(
                    Icons.perm_identity,
                    color: Colors.black,
                  ),
                  onPressed: () {
                    User user = FirebaseAuth.instance.currentUser!;
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => UserHandling(
                          uid: user.uid,
                        ),
                      ),
                    );
                  })

Here it’s the code for user HadelingPage

class UserHandling extends StatefulWidget {
  final String uid;

  const UserHandling({super.key, required this.uid});

  @override
  State<UserHandling> createState() => UserHandlingState();
}

class UserHandlingState extends State<UserHandling> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: StoryProfile(
          uid: widget.uid,
          currentUserID: widget.uid,
        ),
      ),
    );
  }
}

Here it’s the code for StoryPage:

class StoryProfile extends StatefulWidget {
  final String uid;
  final String currentUserID;

  const StoryProfile({
    super.key,
    required this.uid,
    required this.currentUserID,
  });

  @override
  State<StoryProfile> createState() => StoryProfileState();
}

class StoryProfileState extends State<StoryProfile> {
  List<Story> storiesList = [];
  PanelController panelController = PanelController();
  Color bgColor = Colors.transparent;

  late String currentUser;

  @override
  void initState() {
    super.initState();
    currentUser = FirebaseAuth.instance.currentUser!.uid;
    FirebaseFirestore.instance
        .collection('Users/${widget.uid}/Story')
        .get()
        .then((value) {
      if (value.docs.isEmpty) {
        panelController.close();
      }
      for (var element in value.docs) {
        storiesList.add(Story(
          url: (element.data() as Map)['url'],
          media: (element.data() as Map)['media'],
          id: element.id,
        ));
      }
      setState(() {});
      getStoryData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SlidingUpPanel(
        color: bgColor,
        controller: panelController,
        onPanelOpened: () => setState(() => bgColor = Colors.white),
        onPanelClosed: () => setState(() => bgColor = Colors.transparent),
        panelBuilder: (ScrollController sc) {
          UserPage pg = UserPage();
          pg.scrollController = sc;
          return pg;
        },
        collapsed: const Center(
          child: Column(
            children: [
              Icon(
                Icons.keyboard_arrow_up,
                color: Colors.white,
              ),
              Text(
                "SwipeUp to see more information",
                style: TextStyle(color: Colors.white),
              ),
            ],
          ),
        ),
        body: storiesList.isNotEmpty
            ? StoryScreen(
                stories: storiesList,
                uid: currentUser,
                currentUserID: currentUser,
              )
            : const Center(
                child: Text(
                  'Aici trebuie adaugate imagini/videoclipuri cu serviciile dvs. cu scopul de promovarenFolositi butonul "adauga story" ',
                  textAlign: TextAlign.center,
                ),
              ),
      ),
    );
  }

  void getStoryData() async {
    QuerySnapshot<Map<String, dynamic>> query = await FirebaseFirestore.instance
        .collection('Users/$currentUser/Story')
        .get();
    storiesList.clear();
    if (query.docs.isNotEmpty) {
      for (DocumentSnapshot<Map> doc in query.docs) {
        setState(() {
          storiesList.add(Story.fromDocument(doc));
        });
      }
    }
  }
}

And I want that icon button to send the user automatically to UserPage that is in the StoryScreen , but if I add instead of UserHandling(uid: user.uid, ), just UserPage() it’s not working, gives red screen

Here it’s the userPage

        class UserPage extends StatefulWidget {
          late ScrollController scrollController;
        
          UserPage({super.key});
        
          @override
          State<UserPage> createState() => UserProfile();
        }
        
        class UserProfile extends State<UserPage> {
          bool isFileImage = false;
          late User user;
          late File pickedFile;
          String? userImage;
          String? address;
          String? precise_address;
          String? userName;
          String? facebookUrl;
          String? instagramUrl;
          String? tikTokUrl;
          TextEditingController facebookController = TextEditingController();
          TextEditingController instagramController = TextEditingController();
          TextEditingController tiktokController = TextEditingController();
          late String userId;
          Random randomGenerator = Random();
        
          String? searchString;
          String? country;
        
          QuerySnapshot? querySnapshot;
        
          @override
          void initState() {
            super.initState();
            initUser();
          }
        
          initUser() async {
            user = FirebaseAuth.instance.currentUser!;
            userId = user.uid;
            logger.e("user id at init user =$userId");
            getSocialData();
            getData();
          }
        
          final TextEditingController _userNameController = TextEditingController();
        
          late File _image;
          final picker = ImagePicker();
        
          Future getImage() async {
            final pickedFile = await picker.pickImage(source: ImageSource.gallery);
            if (pickedFile != null) {
              setState(() {
                _image = File(pickedFile.path);
              });
              Reference storageReference = FirebaseStorage.instance.ref();
              Uint8List imageData = _image.readAsBytesSync();
              storageReference
                  .child("Users Profile")
                  .child(userId)
                  .putData(imageData)
                  .then((uploadTask) async {
                var dowurl = await uploadTask.ref.getDownloadURL();
                String url = dowurl.toString();
        
                Map<String, dynamic> urlNull = {
                  'avatarUrl': url,
                };
                DocumentReference prereference =
                    FirebaseFirestore.instance.collection('Users').doc(userId);
        
                await FirebaseFirestore.instance.runTransaction((transaction) async {
                  transaction.update(prereference, urlNull);
                });
              });
            }
          }
    Future<void> displayPrediction(Prediction p, BuildContext context) async {
        var placeId = p.placeId;
        var address = await FlGeocoder(Constants.googlePlaceKey)
            .findAddressesFromPlaceId(placeId!);
        setState(() {
          searchString = p.description!;
        });
        FirebaseFirestore.instance.collection('Users').doc(userId).update({
          "precise_location": searchString,
        });
        country = address.first.country!.longName;
      }
    
      var addresses;
      var first;
      double lat = 0.0;
      double long = 0.0;
    
      @override
      void didChangeDependencies() async {
        super.didChangeDependencies();
      }
    
      @override
      Widget build(BuildContext context) {
        void viewReview(var ratings, String name, String review, String avatarUrl) {
          showGeneralDialog(
            context: context,
            barrierDismissible: false,
            transitionDuration: const Duration(
              milliseconds: 400,
            ), // how long it takes to popup dialog after button click
            pageBuilder: (_, __, ___) {
              // your widget implementation
              return Container(
                color: Colors.black.withOpacity(0.4),
                child: Scaffold(
                  backgroundColor: Colors.transparent,
                  appBar: AppBar(
                    backgroundColor: Colors.transparent,
                    automaticallyImplyLeading: false,
                    actions: [
                      IconButton(
                        icon: const Icon(
                          Icons.close,
                          color: Colors.white,
                        ),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                    ],
                  ),
                  body: SafeArea(
                    // top: false,
                    child: Container(
                      padding: const EdgeInsets.all(8.0),
                      child: Container(
                        // color: Colors.white,
                        // height: MediaQuery.of(context).size.height * 0.9,
                        // width: MediaQuery.of(context).size.width * 1,
                        child: ListView(
                          children: [
                            Container(
                              // width: 200,
                              // margin: EdgeInsets.only(
                              //     top: 8, bottom: 8, right: 12),
                              margin: const EdgeInsets.only(
                                  right: 12, top: 8, bottom: 0),
                              padding: const EdgeInsets.all(11),
                              // width: MediaQuery.of(context)
                              //         .size
                              //         .width -
                              //     140,
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  boxShadow: [
                                    BoxShadow(
                                        color: Colors.black.withOpacity(0.1),
                                        blurRadius: 2,
                                        spreadRadius: 1)
                                  ],
                                  borderRadius: BorderRadius.circular(8)),
                              child: Column(
                                children: [
                                  Row(
                                    children: [
                                      CircleAvatar(
                                        backgroundImage: const AssetImage(
                                            'assets/images/profilepic.png'),
                                        child: Image.network(avatarUrl),
                                      ),
                                      const SizedBox(width: 8),
                                      Text(name,
                                          style: const TextStyle(
                                              fontWeight: FontWeight.bold)),
                                      const SizedBox(width: 50),
                                      Row(
                                        children: [
                                          _buildRatingStars(ratings),
                                        ],
                                      )
                                    ],
                                  ),
 Container(
                                margin: const EdgeInsets.only(top: 8),
                                width: MediaQuery.of(context).size.width - 140,
                                child: Text(
                                  review,
                                  textScaleFactor: 1.1,
                                ),
                              ),
                              TextButton(
                                style: TextButton.styleFrom(
                                  shape: const StadiumBorder(),
                                  backgroundColor: Colors.black,
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                                child: const Text(
                                  'Close',
                                  style: TextStyle(
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          );
        },
      );
    }

    return ListView(
      controller: widget.scrollController,
      padding: EdgeInsets.zero,
      children: <Widget>[
        SizedBox(
          height: MediaQuery.of(context).size.height * 0.32,
          child: Stack(
            children: <Widget>[
              Positioned(
                top: MediaQuery.of(context).size.height * 0.06,
                left: MediaQuery.of(context).size.width * 0.09,
                child: Row(
                  children: [Center(
                // left: 24,
                // top: MediaQuery.of(context).size.height * 0.17,
                child: SizedBox(
                  height: 84,
                  width: 84,

                  //profilepic

                  child: userImage != 'default'
                      ? CircleAvatar(
                          radius: 10,
                          backgroundImage: NetworkImage(userImage ?? ""))
                      : const CircleAvatar(
                          radius: 10,
                          backgroundImage:
                              AssetImage('assets/images/profilepic.png'),
                        ),
                ),
              ),
              Positioned(
                right: 24,
                top: MediaQuery.of(context).size.height * 0.2,
                child: Row(
                  children: <Widget>[
                    SizedBox(
                      height: 32,
                      width: 100,
                      child: ElevatedButton(
                          onPressed: () async {
                            await Alert(
                              context: context,
                              title: "",
                              desc:
                                  "Adauga video-uri sau imagini cu afacerea ta",
                              buttons: [
                                DialogButton(
                                  onPressed: () => addPicture(uploadTypes.STORY,
                                      uploadTypes.IMAGE, context),
                                  width: 120,
                                  child: const Text(
                                    "Image",
                                    style: TextStyle(
                                        color: Colors.white, fontSize: 20),
                                  ),
                                ),
                                DialogButton(
                                  onPressed: () => addPicture(uploadTypes.STORY,
                                      uploadTypes.VIDEO, context),
                                  width: 120,
                                  child: const Text(
                                    "Video",
                                    style: TextStyle(
                                        color: Colors.white, fontSize: 20),
                                  ),
                                ),
                              ],
                            ).show();
                          },
                          child: const Text(
                            "Adauga Story",
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 12,
                            ),
                          )),
                    ),
                    const SizedBox(
                      width: 16,
                    ),
                    GestureDetector(
                      onTap: () async {
                        DocumentSnapshot snapshot = await FirebaseFirestore
                            .instance
                            .collection('Users')
                            .doc(userId)
                            .get();
                        UserModel user = UserModel.fromDocument(snapshot);
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => SettingsPage(user: user)),
                        );
                      },
                      child: Container(
                        height: 32,
                        width: 32,
                        decoration: const BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage("assets/images/settings.png"),
                                fit: BoxFit.cover),
                            shape: BoxShape.circle,
                            color: Colors.white),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        const SizedBox(
          height: 20,
        ),
        Row(children: [
          const SizedBox(
            width: 30,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[

2

Answers


  1. for a faster solution and assuming you are using sliding_up_panel plugin, you can set the parameter defaultPanelState to PanelState.OPEN and panelSnapping to false and set the maxHeight to screen height (MediaQuery.of(context).size.height).

     @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: SlidingUpPanel(
           defaultPanelState: PanelState.OPEN,
           panelSnapping: false,
           maxHeight: MediaQuery.of(context).size.height,
            color: bgColor,
            controller: panelController,
            onPanelOpened: () => setState(() => bgColor = Colors.white),
            onPanelClosed: () => setState(() => bgColor = Colors.transparent),
            panelBuilder: (ScrollController sc) {
              UserPage pg = UserPage();
              pg.scrollController = sc;
              return pg;
            },
    

    for a more efficient solution please provide the UserPage() widget and the error stack trace that occurs when you pass UserPage() directly instead of the user handling page.

    Login or Signup to reply.
  2. Given the error: LateInitializationError: Field "scrollerController" has not been initialized you need to initialize your scrollController inside initUser() and there is no need to put it in the parent class of your State class so it should be like this.

    first delete or comment declaration of scrollController

    class UserPage extends StatefulWidget {
              //late ScrollController scrollController;
            
              UserPage({super.key});
            
              @override
              State<UserPage> createState() => UserProfile();
            }
    

    Secondly initialize it in your userInit() function:

     @override
              void initState() {
                super.initState();
                initUser();
              }
            
              initUser() async {
                scrollerController = ScrollerController();
                user = FirebaseAuth.instance.currentUser!;
                userId = user.uid;
                logger.e("user id at init user =$userId");
                getSocialData();
                getData();
              }
    

    Finally call it directly when you use it (not widget.scrollerController):

    return ListView(
          controller: scrollController,
          padding: EdgeInsets.zero,
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search