How to authenticate anonymously in flutter app with realm

I want to authenticate the user anonymously in flutter. Kindly help, document is insufficient for the beginner in flutter and realm

Hi @Zubair_Rajput!
You first have to allow the anonymous authentication provider on your App Service at http://realm.mongodb.com. You can see here how to do it.
Then from the Flutter app you can create anonymous credentials and login with them. Follow this document.

You can also see our tests at the repo

The code should look like:

final appConfig = AppConfiguration(APP_ID);
final app = App(appConfig);
final anonCredentials = Credentials.anonymous();
await app.logIn(anonCredentials);

In react native I know how to do that but in flutter I am new and you can see the screenshot.
I am setting up app configuration but I am having errors. Kindly help.
I can also show my full code If you required.

Did you try the code that I sent above? Just set the correct appId in AppConfiguration and run it. This should work.
What errors do you receive?

Hello Desislava, thanks for the replies,
Yes I tried to write the above line you suggested. kindly help

In the above screenshot you can see red zigzag error line. When I hover over it it says

*error message*:   The instance member of 'appId' can't 
be accessed in an initializer. 
Try replacing the reference
to the instance member with a different expression.
import 'package:flutter/material.dart';
import 'package:realm_dart/realm.dart';

import 'package:cric_orion/src/constants/Colors.dart';
import 'package:go_router/go_router.dart';

class SettingScreen extends StatefulWidget {
  const SettingScreen({super.key});

  @override
  State<SettingScreen> createState() {
    return _SettingScreen();
  }
}

class _SettingScreen extends State<SettingScreen> {
  String appId = "vishwa-sports-b2x-xxxxx";
  final appConfig = AppConfiguration(appId);
  final app = App(appConfig);
  final anonCredentials = Credentials.anonymous();
  

  @override
  Widget build(context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        centerTitle: true,
        leading: IconButton(
          padding: EdgeInsets.zero,
          color: ColorList.five,
          onPressed: () => context.go('/profile'),
          icon: const Icon(Icons.chevron_left),
        ),
        leadingWidth: 50,
        elevation: 0,
        title: const Text(
          "Settings",
          style: TextStyle(color: ColorList.five),
        ),
        backgroundColor: ColorList.sbYellow,
      ),
      body: Column(
        children: [
          const CartContainer(),
          const CartContainer(),
          const CartContainer(),
          const CartContainer(),
          const CartContainer(),
          Expanded(
            child: Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                width: 300,
                height: 50,
                margin: const EdgeInsets.only(bottom: 30),
                child: ElevatedButton(
                  style: ButtonStyle(
                    foregroundColor:
                        MaterialStateProperty.all<Color>(ColorList.five),
                    backgroundColor: MaterialStateProperty.all<Color>(
                      ColorList.sbYellow,
                    ),
                    shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                      RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(25),
                      ),
                    ),
                  ),
                  onPressed: () => null,
                  child: const Text(
                    "Logout",
                    style: TextStyle(
                      fontSize: 15,
                    ),
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

class CartContainer extends StatelessWidget {
  const CartContainer({super.key});

  @override
  Widget build(context) {
    return Container(
      height: 70,
      decoration: const BoxDecoration(
        border: Border(
          bottom: BorderSide(color: ColorList.grey, width: .5),
        ),
      ),
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () => {
          context.go('/profile/setting/feedback'),
        },
        child: Row(
          children: [
            Expanded(
              flex: 1,
              child: Container(
                height: double.infinity,
                child: Center(
                  child: Container(
                    height: 40,
                    width: 40,
                    padding: const EdgeInsets.all(5),
                    decoration: BoxDecoration(
                      color: ColorList.lightGrey,
                      borderRadius: BorderRadius.circular(40),
                    ),
                    child: const Icon(
                      Icons.all_inclusive,
                      size: 20,
                    ),
                  ),
                ),
              ),
            ),
            Expanded(
              flex: 3,
              child: Container(
                height: double.infinity,
                alignment: Alignment.centerLeft,
                margin: const EdgeInsets.only(left: 5),
                child: const Text(
                  "Re-calibrate Stricker",
                  style: TextStyle(fontSize: 16, color: ColorList.greySecond),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

@Zubair_Rajput, I’m not sure what exactly could be the issue with the red lines, but I see from the imported packages that you have imported the dart package realm_dart.
For a Flutter app you should import realm package. You should remove realm_dart and add realm realm | Flutter Package

flutter pub remove realm_dart
flutter pub add realm

Then import this.

import 'package:realm/realm.dart

Hello Mam,

Actually placing appId and App AppConfiguration at the top solve the problem


String appId = "safexxxtraxx-xxxxxx";
final appConfig = AppConfiguration(appId);

// APP ENTRY POINT
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

Thanks for the supports

2 Likes

G’day, @Zubair_Rajput ,

Glad to know your issue was resolved. Could you please confirm if you also changed the package names?

I look forward to your response.

Thanks,
henna

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.