-1

I'm trying to route to specific id /product/:id but when i click on my card to navigate it shows an error , but when i do hot reload it works.

**Here is the error **> type 'Null' is not a subtype of type 'String'

go-router in main.dart

final GoRouter _router = GoRouter(
    debugLogDiagnostics: true,
  initialLocation: '/',
  routes: [
    GoRoute(
      path: '/',
      builder: (BuildContext context, GoRouterState state) {
        return const MainPage();
      },
    ),
      GoRoute(
        path: '/product/:id',
        builder: (BuildContext context, GoRouterState state)=>  DetailsView(id:state.params["id"]!)
      ),
      GoRoute(
        path: '/homepage',
        builder: (BuildContext context, GoRouterState state) {
          return const HomePage();
        },
      ),
  ],
);

here is how i route to my product/:id (I'm using Carousel Slider).

Widget buildImage(String urlImage, String title, int price, double padding,
        int index, String id, BuildContext context) =>
    GestureDetector(
      **onTap: () {
        context.push("/product/$id");
      },**
      child: Container(
............))) etc

and here is my detailsView page which when navigating to the error appears.


class DetailsView extends StatefulWidget {
  final String id;

  /// Constructs a [DetailsScreen]
  const DetailsView({super.key, required this.id});
  @override
  State<DetailsView> createState() => _DetailsViewState();
}

class _DetailsViewState extends State<DetailsView> {
  var urlImage;
  var description;
  var price;
  var title;
  getProductInfo(id) async {
    devtools.log(id);
    var productRef = await FirebaseFirestore.instance
        .collection('products')
        .doc(id)
        .get()
        .then((doc) => {
              urlImage = doc.get("urlImage"),
              description = doc.get("description"),
              price = doc.get("price"),
              title = doc.get("title"),
            });
  }

  @override
  void initState() {
    var id = widget.id;
    getProductInfo(id);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

.....}

type 'Null' is not a subtype of type 'String' , this error appears when i navigate to my page using go-router package

krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
Mohammed Malek
  • 164
  • 1
  • 9

1 Answers1

0

It is because your id is null. Make sure your id is not null before passing it as id in the router by debugPrint.

      onTap: () {
       debugPrint("The value of id is $id"); // Here you should get some string instead of null
       if(id !=null) {context.push("/product/$id");}
      },

Edit: Try using named route (Guaranteed to work)


 GoRoute(
    path: '/product/:id',  
    name: 'product',
    builder: (context, state) => DetailsView(
      id: state.params['id']
    ),
  ),

And use:

 onTap: () {
   context.pushNamed("product", params: {'id1': id});
 },
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88